Start by seeding the pseudorandom number generator. For example,
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, 7)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
fmt.Println(string(b))
}
Output:
jfXtySC
The Go Playground
About the Playground
In the playground the time begins at 2009-11-10 23:00:00 UTC
(determining the significance of this date is an exercise for the
reader). This makes it easier to cache programs by giving them
deterministic output.
Therefore, in the Go playground, time.Now().UnixNano()
always returns the same value. For a random seed value, run the code on your computer.
For any Unicode code point (Go rune),
package main
import (
"fmt"
"math/rand"
"time"
)
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
chars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ世界!@=")
r := make([]rune, 50)
for i := range r {
r[i] = chars[rand.Intn(len(chars))]
}
fmt.Println(string(r))
}
Output:
世QRYSp=@giJMIKly=tXRefjtVkeE!yHhTSQHvLyUYdRNIBbILW