randomgo

# Generating random numbers over a range in Go

All the integer functions in `math/rand` generate non-negative numbers.

``````rand.Int() int              // [0, MaxInt]
rand.Int31() int32          // [0, MaxInt32]
rand.Int31n(n int32) int32  // [0, n)
rand.Int63() int64          // [0, MaxInt64]
rand.Int63n(n int64) int64  // [0, n)
rand.Intn(n int) int        // [0, n)
``````

I would like to generate random numbers in the range [-m, n). In other words, I would like to generate a mix of positive and negative numbers.

Solution

• For Go 1.22+:

Use the `math/rand/v2` package.

``````import "math/rand/v2"

func randRange(min, max int) int {
return rand.IntN(max-min) + min
}
``````

For Go 1.21 and earlier:

``````import "math/rand"

func randRange(min, max int) int {
return rand.Intn(max-min) + min
}
``````

Please note that this returns numbers in the range [min, max), meaning that `max` is never returned. For example, `randRange(1, 3)` would return `1` and `2` only. It would never return `3`. If you want numbers in the range [min, max], just add `1` as shown below:

``````return rand.IntN(max+1-min) + min
``````