Friday, October 7, 2022
HomeGolangGenerate a random string in Go (Golang)

Generate a random string in Go (Golang)



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.

 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
bundle most important

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

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

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

func most important() {
    rand.Seed(time.Now().UnixNano())

    fmt.Println(randomString(20))
}

The way it works

The randomString() perform

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

  2. 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 the n (measurement of the output string) random characters and add them to the beforehand created strings.Builder. Deciding on random characters is completed by the rand.Intn() perform, which returns a random quantity between 0 and X, the place X is the argument of the rand.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 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

    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:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments