Generating random numbers over a range in Go

Golang has built-in support for random number generation in the standard library. Specifically there is the math/rand package which implements pseudo-random number generators.

However there is no function to generate a random integer between two defined values. But there is one that generates a random integer given between zero and a max value

func Intn(n int) int

func Intn(n int) int

Intn returns, as an int, a non-negative pseudo-random number in [0,n) from the default Source. It panics if n <= 0.

We can effectively use this function to generate a random number between two values

package main
        
import "fmt"
import "math/rand"
        
func main() {
    min := 10
    max := 30
    fmt.Println(rand.Intn(max - min) + min)
}
        

This thing works quite well, however if you try to run it several times you will see always the same number in output

Indeed on the official documentation we can read

Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

The proper example should then become

package main
        
import "fmt"
import "math/rand"
import "time"
        
func main() {
    rand.Seed(time.Now().UnixNano())
    min := 10
    max := 30
    fmt.Println(r.Intn(max - min) + min)
}
        

Bear in mind, for random numbers suitable for security-sensitive work, use the crypto/rand package instead.


Want a job board with no recruiters and clear salary ranges?
Find your next Go Job on Golang Cafe