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.Builder
initialization13 14
sb := strings.Builder{} sb.Grow(n)
In the first step, we create the
strings.Builder
structure and grow its capacity to the size of the output string:n
. Thestrings.Builder
is 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 17
for i := 0; i < n; i++ { sb.WriteByte(charset[rand.Intn(len(charset))]) }
In the
for
loop, 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
, whereX
is 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 thecharset
string at this random index. Doing thisn
times 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
charset
constant. - Return the result
18
return sb.String()
By calling the
Builder.String()
method, we get the accumulated string that we return from the function.
The main()
function
- Seed
22
rand.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()
function24
fmt.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:
XqtscOKPBRGnAXMnzKzq
APHQenfBuRrTlMzDShyr
dfXgMuGTnfUkLVZQXonw