Generating a random string with given length in Go
We sometimes need to generate random strings like to generate passwords/ tokens etc.
Following program shows how to do that in Golang
package main
import (
"fmt"
"math/rand"
"time"
)
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
func main() {
rand.Seed(time.Now().UnixNano()) // for random to work
fmt.Printf(GenerateRandomString(10))
}
func GenerateRandomString(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
You can also run the program to see the output here https://onecompiler.com/go/3xm8qaba3