To generate a random string in Go, you must write a customized perform that randomly selects characters from a given charset as many instances because the set size of the output and combines them to kind a random, fixed-length string.
|
|
The way it works
The randomString()
perform
- The
strings.Builder
initialization13 14
sb := strings.Builder{} sb.Develop(n)
In step one, we create the
strings.Builder
construction and develop its capability to the dimensions of the output string:n
. Thestrings.Builder
is used to effectively concatenate strings, minimizing the variety of copies and reminiscence allocations. In our perform, it’s used to construct and retailer the output random string.See our put up on the right way to concatenate strings in Go.
- Random character producing loop
15 16 17
for i := 0; i < n; i++ { sb.WriteByte(charset[rand.Intn(len(charset))]) }
Within the
for
loop, we generate then
(measurement of the output string) random characters and add them to the beforehand createdstrings.Builder
. Deciding on random characters is completed by therand.Intn()
perform, which returns a random quantity between 0 andX
, the placeX
is the argument of therand.Intn()
perform. In our case,charset[rand.Intn(len(charset))]
implies that we choose a random quantity within 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
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: