Generating Random Numbers
Let’s learn how to generate random numbers in Go.
We'll cover the following
Random number generation is an art as well as a research area in computer science. This is because computers are purely logical machines, and it turns out that using them to generate random numbers is extremely difficult!
Random numbers generation in Go
Go can help us with that using the functionality of the math/rand
package.
Seed generation
Each random number generator needs a seed to start producing numbers. The seed is used for initializing the entire process and is extremely important because if we always start with the same seed, we will always get the same sequence of pseudorandom numbers. This means that everybody can regenerate that sequence, and that particular sequence will not be random after all. However, this feature is really useful for testing purposes. In Go, the rand.Seed()
function is used for initializing a random number generator.
Note: For details about random number generation, please refer to the second volume of The Art of Computer Programming by Donald E. Knuth (Addison-Wesley Professional, 2011).
Coding example
The following function, which is part of randomNumbers.go
, generates random numbers in the [min, max)
range.
Get hands-on with 1200+ tech skills courses.