Understanding Repeated Random Numbers in Go's rand.Intn
The Go standard library provides the rand package for generating random numbers. However, the rand.Intn(n) function consistently returns the same value when invoked repeatedly. This behavior raises the question of why it occurs. The answer lies in two key factors.
Uninitialized Global Source
By default, the rand package uses a global Source that generates a deterministic sequence of values. This means that the output of functions like rand.Intn() remains the same unless this Source is initialized with a seed.
To fix this, one must set a random seed using rand.Seed(). A common approach is to use the timestamp obtained from time.Now().UnixNano() as the seed:
rand.Seed(time.Now().UnixNano())
This initializes the Source and introduces randomness into the sequence generated by rand.Intn().
Go Playground Caching
Another factor contributing to the observed behavior is the Go Playground. This online tool caches the output of code snippets, which may lead to the same random number sequence being displayed consistently, regardless of actual randomness.
To avoid this caching issue, it is recommended to run the code locally. This ensures that the random seed is generated at execution time, resulting in a unique sequence of values.
By initializing the global Source and avoiding the Go Playground caching, one can ensure that rand.Intn() generates truly random numbers in Go programs.
The above is the detailed content of Why Does Go's `rand.Intn()` Return the Same Number Repeatedly?. For more information, please follow other related articles on the PHP Chinese website!