Go provides a built-in package named math/rand
to generate pseudorandom numbers.
The pseudorandom numbers are a deterministic sequence of numbers that depend on a seed
value. In order to generate random numbers on every execution, we need to set the seed every time.
Note: You can learn more about seed here.
In this shot, we’ll see how to generate a random number in a given range using the rand.Intn()
function of the math/rand
package.
rand.Intn()
functionrand.Intn(n)
The rand.Intn()
function accepts a number n
and returns an unsigned pseudorandom integer in the interval [0, n)
. It will throw an error if the value of n
is less than zero.
We can use the following syntax to generate a random number in a specific range.
rand.Intn(max-min) + min
Here, max
is the upper bound and min
is the lower bound. It will return a random number in the interval [min, max)
.
Let’s see an example to generate a random number between 1 and 5.
We will use the following packages.
fmt
formats the output.math/rand
generates random numbers.time
sets the seed.package mainimport ("fmt""math/rand""time")func main() {min := 1max := 5// set seedrand.Seed(time.Now().UnixNano())// generate random number and print on consolefmt.Println(rand.Intn(max - min) + min)}
min
and max
that specify the lower and the upper bound respectively.time.Now().UnixNano()
function. This function will return the number of seconds passed from January 1, 1970.rand.Intn()
function and output it on the console.