Go by Example

Random Numbers

math/rand/v2 for general-purpose randomness, global functions vs local Source, and crypto/rand for cryptographically secure randomness.

math/rand/v2 (Go 1.22 or later) generates pseudo-random values, numbers that look random but come from a repeatable calculation. Use it for simulations and other tasks where secrecy does not matter. Its global functions are seeded automatically.

IntN(n) returns an integer from zero up to, but not including, n. Use Shuffle to reorder items in place.

package main
 
import (
    "fmt"
    "math/rand/v2"
)
 
func main() {
    fmt.Println(rand.IntN(100))
    cards := []string{"A", "K", "Q", "J"}
    rand.Shuffle(len(cards), func(i, j int) {
        cards[i], cards[j] = cards[j], cards[i]
    })
    fmt.Println(cards)
}

In production

Do not use math/rand/v2 for passwords or secret keys because its results can be predicted. Use crypto/rand, which gets unpredictable bytes from the operating system, for secrets. A seed is the starting value for the calculation. In tests, use the same seed each run to get the same sequence of values.

Enjoyed this? Get more software craft delivered to your inbox.