BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Random Number

Go 1.23

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 (or NewSource) for variety.
  • crypto/rand: Use this for security-sensitive data.

Code Breakdown

12
Seeding the generator. We use the current time in nanoseconds as the seed. This ensures that every time the program runs, the starting point for the random sequence is different.
17
Generating a random integer. 'rand.Intn(100)' gives us a number from 0 up to 99. It will never return 100.
27
Generating a range. To get a number between 50 and 100, we generate a number between 0 and 50 ('max - min'), and then add the minimum value (50) to it.