About rand.Seed()
As of Go 1.20, there is no reason for calling rand.Seed()
using a random value to initiate the random number generator. However, using rand.Seed()
is not going to break existing code. To get a specific sequence of numbers, it is recommended to call New(NewSource(seed))
instead.
This is illustrated in ch15/randSeed.go
—the relevant Go code is the following:
src := rand.NewSource(seed)
r := rand.New(src)
for i := 0; i < times; i++ {
fmt.Println(r.Uint64())
}
The rand.NewSource()
call returns a new (pseudo) random source based on the given seed. Therefore, if called with the same seed, it is going to return the same sequence of values. The rand.New()
call returns a new *rand.Rand
variable, which is what generates the (pseudo) random values. Due to the call to Uint64()
, we are generating unsigned int64
values.
Running randSeed.go
produces the following output:
$ go run randSeed.go 1
Using seed: 1
5577006791947779410...