Solving Repetitive Random Number Generation in Go
In Go, the rand.Intn(n int) int function returns a pseudo-random integer within the range [0, n). However, you've encountered an issue where it prints the same number consistently.
The documentation suggests that rand.Intn uses the default Source, which generates a deterministic sequence of values. To customize the behavior and ensure randomness, you must properly seed the random number generation.
To seed the random number generator, call the rand.Seed(seed int64) function. This function initializes the default Source with a seed value. A common practice is to use the current Unix timestamp:
<code class="go">rand.Seed(time.Now().UnixNano())</code>
By seeding the generator, you ensure that each run of your program produces different random numbers.
If rand.Seed() is not called, the generator acts as if seeded by 1, leading to the observed repetition.
The above is the detailed content of Why Does My Go Code Keep Generating the Same Random Number?. For more information, please follow other related articles on the PHP Chinese website!