Cookies management by TermsFeed Cookie Consent
Russia has invaded Ukraine and already killed tens of thousands of civilians, with many more raped or tortured. It's a genocide. We need your help. Let's fight back against the Russian regime.
Help Ukraine! Fight the Russian regime!

🎲 Generate a random string in Go

introduction random strings

Please consider supporting us by disabling your ad blocker

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
    "fmt"
    "math/rand"
    "strings"
    "time"
)

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func randomString(n int) string {
    sb := strings.Builder{}
    sb.Grow(n)
    for i := 0; i < n; i++ {
        sb.WriteByte(charset[rand.Intn(len(charset))])
    }
    return sb.String()
}

func main() {
    rand.Seed(time.Now().UnixNano())

    fmt.Println(randomString(20))
}

How it works

The randomString() function

  1. The strings.Builder initialization
    13
    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. The strings.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.

  2. 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 the n (size of the output string) random characters and add them to the previously created strings.Builder. Selecting random characters is done by the rand.Intn() function, which returns a random number between 0 and X, where X is the argument of the rand.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 the charset string at this random index. Doing this n times and adding to the result gives us a random string of length n.

    If you want to limit or add new characters to the set from which the random string is made, modify the charset constant.

  3. 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

  1. Seed
    22
    
    rand.Seed(time.Now().UnixNano())
    

    In the first line of the main() function, we set the timestamp of current time time.Now().UnixNano() as the seed of the pseudorandom number generator. Without it, the rand.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.

  2. Calling the randomString() function
    24
    
    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
    

✌️ 4 ways to create or print string with double quotes in Go

Learn how to create and print double-quoted string
introduction strings

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice