Hey guys, I am messing around on A Tour of Go and The Go Playground trying to get a random number and it doesn't seem to be working. Should the following code work?
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println("My favorite number is", rand.Intn(10))
}
评论:
dlsniper:
liahkim3:The playground caches the results. Also random is deterministic. And finally the time in playground is always the same. See more info by clicking the About section of the playground.
sleepydog:Woo! I was hoping this was the case. It said that rand.Intn was deterministic and to use the Seed method to get a random number so I thought I was doing something wrong. Thanks!
Thomasdezeeuw:Just so you know, if you don't want outsiders to be able to guess what the next number will be, seeding an RNG with the local time is undesirable. In such a use case, you should use the OS's entropy source, which in Go is exposed through the Reader variable in the crypto/rand package. Something like this: https://play.golang.org/p/ticW5xkU4c
dchapes:You should be using crypto/rand for generating anything that needs to be random (or the closed thing to it). It is however a little slower then math/rand, so you could seed math/rand with a seed generated by crypto/rand.
On some systems the entropy pool for the system wide
/dev/urandom
(or equivalent) is limited. Unless you really need cryptographic secure random numbers you should not usecrypto/rand
.A really good compromise is to use
crypto/rand
to seedmath/rand
(as both you and sleepydog said above). IMO, there should be a convenience function to do this in the standard library (ala BSD's srandomdev(3) which also can set the PRNG state to more values than a single int64 can).