To generate a random string in Go, you need to write a custom function that randomly selects characters from a given charset as many times as the set length of the output and combines them to form a random, fixed-length string.
| |
How it works
The randomString() function
- The
strings.Builderinitialization13 14sb := strings.Builder{} sb.Grow(n)In the first step, we create the
strings.Builderstructure and grow its capacity to the size of the output string:n. Thestrings.Builderis used to efficiently concatenate strings, minimizing the number of copies and memory allocations. In our function, it is used to build and store the output random string.See our post on how to concatenate strings in Go.
- Random character generating loop
15 16 17for i := 0; i < n; i++ { sb.WriteByte(charset[rand.Intn(len(charset))]) }In the
forloop, we generate then(size of the output string) random characters and add them to the previously createdstrings.Builder. Selecting random characters is done by therand.Intn()function, which returns a random number between 0 andX, whereXis the argument of therand.Intn()function. In our case,charset[rand.Intn(len(charset))]means that we select a random number in the half-open interval [0,len(charset)), and then get a character from thecharsetstring at this random index. Doing thisntimes and adding to the result gives us a random string of lengthn.If you want to limit or add new characters to the set from which the random string is made, modify the
charsetconstant. - Return the result
18return sb.String()By calling the
Builder.String()method, we get the accumulated string that we return from the function.
The main() function
- Seed
22rand.Seed(time.Now().UnixNano())In the first line of the
main()function, we set the timestamp of current timetime.Now().UnixNano()as the seed of the pseudorandom number generator. Without it, therand.Intn()function would return the same result every time, and the output string would remain the same between runs of the program. This is because the pseudo-random number generators produce new values by performing some operations on the previous value, and when the initial value (the seed value) stays the same, you get the same output numbers. - Calling the
randomString()function24fmt.Println(randomString(20))In the last line, we generate a random string of length 20 and print it to the standard output. Run the program several times to see a different string each time:
XqtscOKPBRGnAXMnzKzqAPHQenfBuRrTlMzDShyrdfXgMuGTnfUkLVZQXonw
