How to Generate Random String of Fixed Length in Golang

Jay Singh Feb 02, 2024
How to Generate Random String of Fixed Length in Golang

Many different algorithms need the production of random strings of a specific length. This article will show you how to produce a random string of a fixed length in Golang in several different methods.

Use math/rand to Generate Random String of Fixed Length in Golang

Go’s math/rand package provides pseudorandom number generation. We’ll use the package in this example and pass a random string to receive the output of a fixed-length string.

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println(RandomString(30))
}

func RandomString(n int) string {
	var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

Output:

XVlBzgbaiCMRAjWwhTHctcuAxhxKQF

For another example, the method accepts a string containing each letter and produces a string by picking a letter at random from it.

package main

import (
	"fmt"
	"math/rand"
)

func RandomString(n int) string {
	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

	s := make([]rune, n)
	for i := range s {
		s[i] = letters[rand.Intn(len(letters))]
	}
	return string(s)
}

func main() {
	fmt.Println(RandomString(13))
}

Output:

BpLnfgDsc2WD8

Let’s have a last example to fully understand how to generate a fixed-length string in Golang.

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println("Random String")
	fmt.Println()
	fmt.Println("11 chars: " + RandomString(11))
	fmt.Println("20 chars: " + RandomString(20))
	fmt.Println("32 chars: " + RandomString(32))
}

func RandomString(n int) string {
	var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

	b := make([]rune, n)
	for i := range b {
		b[i] = letter[rand.Intn(len(letter))]
	}
	return string(b)
}

Output:

Random String

11 chars: BpLnfgDsc2W
20 chars: D8F2qNfHK5a84jjJkwzD
32 chars: kh9h2fhfUVuS9jZ8uVbhV3vC5AWX39IV

Related Article - Go String