golang

Golang Generate Random String

The ability to generate a random string in your program is one we might take for granted. However, it comes very handy when we need to work with various algorithms.

In this brief article, we will discuss how you can generate a random string using the Go programming language.

Random String

The simplest method for creating a random string is to randomly select a string from a sequence of strings.

We can start by creating a rune containing all alphanumerical characters. We then select random characters from it and concatenate them to create a random string.

Consider the implementation shows below:

package main
import (
    "fmt"
    "math/rand"
)
func main() {
    fmt.Println(generate(10))
}
func generate(n int) string {
    var chars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321")
    str := make([]rune, n)
    for i := range str {
        str[i] = chars[rand.Intn(len(chars))]
    }
    return string(str)
}

In the above example, we create a function that takes the length of the random string to generate. We then use the for loop and the range operator to randomly select characters of the specified length.

We then return the string. Once we run the program, we should get the output as:

$ go run random_string.go
BpLnfgDsc8

Random String – Base64

We can also use other tricks such as base64 encoding to generate a random string. Keep in mind that the methods in this guide are not secure for a password.

An example is as shown:

str := "sample string"
random_str := base64.StdEncoding.EncodeToString([]byte(str))
fmt.Println(random_str)

The code above should take the provided string and encode it to base64. The resulting output is as:

c2FtcGxlIHN0cmluZw==

Conclusion

This guide covers the most basic methods of generating a random string in Go. There are a lot more implementations you can use.

Happy coding!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list