Random numbers in Go

Random numbers

Go's math/rand package provides functionality for generating random numbers. The package includes a Rand type representing a source of random numbers, and functions for generating random numbers of various types.

How to generate a random integer in Go

Here's an example of how to generate a random integer between 0 and 99:

    package main

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

    func main() {
        rand.Seed(time.Now().UnixNano())
        randomInt := rand.Intn(100)
        fmt.Println(randomInt) // Output: a random integer between 0 and 99
    }

In above example, the rand.Seed() function is used to initialize the random number generator with the current time in nanoseconds. This ensures that the sequence of random numbers generated is different every time the program is run. The rand.Intn() function is then used to generate a random integer between 0 and 99.

Here are some other functions you can use to generate random numbers in Go:

  • rand.Intn(n int) int: generates a random integer between 0 and n-1.

  • rand.Int() int: generates a random non-negative integer.

  • rand.Float32() float32: generates a random float between 0 and 1.

  • rand.Float64() float64: generates a random float between 0 and 1.

  • Note that the math/rand package is not suitable for generating cryptographically secure random numbers.

  • If you need to generate random numbers for cryptographic purposes, you should use the crypto/rand package instead.

Previous Article

Next Article