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:
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:
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:
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:
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!