In Go, you can generate random numbers using the math/rand
package. The package provides functions for generating pseudo-random numbers based on a seed value.
Here’s an example that demonstrates how to generate random numbers in Go:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// Set a seed value based on the current time
rand.Seed(time.Now().UnixNano())
// Generate a random integer between 0 and 100
randomInt := rand.Intn(101)
fmt.Println(randomInt)
// Generate a random float between 0.0 and 1.0
randomFloat := rand.Float64()
fmt.Println(randomFloat)
}
In this example, we import the fmt
, math/rand
, and time
packages. The math/rand
package provides the functions to generate random numbers, and the time
package is used to set a unique seed value based on the current time.
We set the seed value using rand.Seed(time.Now().UnixNano())
, which ensures that a different seed is used for each program execution, resulting in different sequences of random numbers.
To generate a random integer between 0 and 100, we use rand.Intn(101)
, where 101
specifies the upper limit (exclusive) for the random number generation. The generated random integer is then printed.
Similarly, to generate a random float between 0.0 and 1.0, we use rand.Float64()
, which returns a random floating-point number in the range [0.0, 1.0). The generated random float is printed.
Note that in order to generate random numbers, it’s important to set the seed value using rand.Seed()
with a value that changes over time to ensure randomness. In this example, we use time.Now().UnixNano()
to obtain the current time in nanoseconds as the seed value.
Remember to import the required packages (fmt
, math/rand
, and time
) and set the seed value before generating random numbers in your Go program.