Go rand.Intn Returns the Same Number
In Go, the rand.Intn() function generates a pseudorandom integer between 0 (inclusive) and n (exclusive). However, users have reported that their code using this function always returns the same value. Why is this happening?
There are two primary reasons for this behavior:
Lack of Initialization:
The rand package maintains a global Source that underlies all its random number generators, including rand.Intn(). By default, this Source is uninitialized, resulting in a deterministic sequence of values. To fix this, call rand.Seed() to initialize the Source with a random value, typically obtained from the system clock:
rand.Seed(time.Now().UnixNano())
The above is the detailed content of Why Does Go's `rand.Intn()` Return the Same Number?. For more information, please follow other related articles on the PHP Chinese website!