Generate Random Strings in Go
Random strings are useful for temporary identifiers, test data, filenames, invitation codes, and security-sensitive tokens. Go offers different random-number sources, and choosing the correct one matters.
1. math/rand for Non-Security Uses For simulations, test fixtures, randomized UI behavior, or other cases where predictability is not a security problem, math/rand is appropriate.
With modern Go, create an explicit generator when you need independent pseudo-random state:
Copy package main import ( "fmt" "math/rand" ) const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" func GenerateRandomString(r *rand.Rand, length int) string { result := make([]byte, length) for i := range result { result[i] = alphabet[r.Intn(len(alphabet))] } return string(result) } func main() { r := rand.New(rand.NewSource(42)) fmt.Println(GenerateRandomString(r, 10)) } A fixed seed is useful for reproducible tests. Do not use math/rand for secrets, session tokens, password-reset tokens, or other authentication material.