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+) generates pseudo-random values for simulations and other non-security uses. Its global functions are automatically seeded.

IntN(n) returns an integer in [0, n). Use Shuffle to randomly reorder elements 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 secrets, passwords, nonces, or session tokens. Use crypto/rand for security-sensitive bytes, then encode them with base64.RawURLEncoding when a URL-safe string is needed. For repeatable tests, create a local generator with rand.New(rand.NewPCG(1, 2)).

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