Skip to content

Go Random Numbers

Go provides two main packages for generating random numbers: math/rand for general use and crypto/rand for security-sensitive tasks.

1. General Random Numbers (math/rand)

By default, math/rand is deterministic (it produces the same numbers every time). You should seed it to get different results.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    // Seed with current time to get different numbers each run
    rand.Seed(time.Now().UnixNano())

    // 1. Random integer between 0 and 99
    fmt.Println(rand.Intn(100))

    // 2. Random float between 0.0 and 1.0
    fmt.Println(rand.Float64())

    // 3. Random float between 5.0 and 10.0
    fmt.Println(5.0 + rand.Float64()*(10.0-5.0))
}

2. Shuffling Slices

A common task is to shuffle a list of items.

1
2
3
4
5
s := []int{1, 2, 3, 4, 5}
rand.Shuffle(len(s), func(i, j int) {
    s[i], s[j] = s[j], s[i]
})
fmt.Println(s)

3. Secure Random Numbers (crypto/rand)

Use this for passwords, tokens, or encryption keys. It is much slower but safe from prediction.

package main

import (
    "crypto/rand"
    "fmt"
)

func main() {
    b := make([]byte, 16)
    _, err := rand.Read(b)
    if err != nil {
        return
    }
    fmt.Printf("%x\n", b)
}

Why use Random Numbers?

  • Simulations: Modeling real-world events.
  • Security: Generating unique IDs or tokens.
  • Testing: Fuzzing your code with random inputs.
  • Games: Dice rolls, card shuffling, or spawning enemies.