Go by Example: Random Number
Generating random numbers requires `math/rand`. Remember to seed the generator for varied results in older Go versions.
Code
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// 1. Seeding (Crucial for Go < 1.20)
// Without this, you get the same numbers every run.
// Go 1.20+ seeds automatically, but explicit seeding is safe.
rand.Seed(time.Now().UnixNano())
// 2. Random Int
// Intn(n) returns a number in [0, n).
fmt.Print("Int [0, 100): ")
fmt.Println(rand.Intn(100))
// 3. Random Float
// Float64() returns a number in [0.0, 1.0).
fmt.Print("Float [0.0, 1.0): ")
fmt.Println(rand.Float64())
// 4. Range [min, max)
// Formula: min + rand.Intn(max - min)
min, max := 50, 100
r := min + rand.Intn(max-min)
fmt.Printf("Range [%d, %d): %d\n", min, max, r)
}
Explanation
Generating random numbers in Go is handled by the math/rand package. A critical concept to understand is "seeding." A pseudo-random number generator (PRNG) starts from a seed value; if you use the same seed, you get the exact same sequence of numbers. Historically, Go developers had to manually seed the generator using the current time (time.Now().UnixNano()) to ensure different results on each run. While Go 1.20+ handles this automatically, understanding seeding remains important for deterministic testing.
The most common function is rand.Intn(n), which returns a random integer between 0 and n-1. For floating-point numbers, rand.Float64() returns a value between 0.0 and 1.0. It is important to note that math/rand is not cryptographically secure. For generating passwords, tokens, or keys, you must use the crypto/rand package, which is slower but unpredictable.
- rand.Intn(n): Random int from 0 to n-1.
- Seeding: Use
rand.Seed(orNewSource) for variety. - crypto/rand: Use this for security-sensitive data.

