I'm a little confused. I have a random string generator, here's the code:
package utils
import (
"fmt"
"math/rand"
)
var chars = []rune("abcdefghijklmnopqrstuvwxyz0123456789")
func RandSeq(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = chars[rand.Intn(len(chars))]
}
fmt.Println(string(b))
return string(b)
}
Every time I run this, it will generate a new random string, but if I restart the server the results will repeat themselves. Here are some results:
go run main.go
fpllngzieyoh43e0133ols6k1hh2gdny
xxvi7hvszwk1b182tvjzjpezi4hx9gvm
kir0xcta0opsb5qipjzb3h3x9kcegta5
m1zcv5drxckn42gb50anxndsckjdwgfw
5japz01zicapy9eqixuc9uehq235v48c
51wgg1gypq4s9miwn1dxkjqd614m58f0
fyy29g6ujmxbouxshy2plmkmhlnmdbfh
f7kq8u26873eql4yyp7fyilbb72nrtlc
go run main.go
fpllngzieyoh43e0133ols6k1hh2gdny
xxvi7hvszwk1b182tvjzjpezi4hx9gvm
kir0xcta0opsb5qipjzb3h3x9kcegta5
m1zcv5drxckn42gb50anxndsckjdwgfw
5japz01zicapy9eqixuc9uehq235v48c
Any idea why this is happening?
You need to Seed the random number generator prior to generating any random numbers. A good value to use is the current unix timestamp:
import (
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
}
Note that you should only seed the RNG once at startup (or after forking), not before each random number generation.
If rand.Seed
is not set, it defaults the seed to 1
, giving you the same random number every time.
Seeding rand
at startup with a random number like rand.Seed(time.Now().UnixNano())
will give you a changing result each time you run your program.
You can also create your own random var like:
var random = rand.New(rand.NewSource(time.Now().UnixNano()))
func main() {
num := random.Intn(10)
fmt.Println(num)
num = random.Intn(10)
fmt.Println(num)
}