How to Generate Random Number in Go: Simple Guide
math/rand package. First, seed the random number generator with rand.Seed() using the current time, then call functions like rand.Intn() to get random integers.Syntax
To generate random numbers in Go, you use the math/rand package. You must seed the generator with rand.Seed() to get different results each run. Then, use functions like rand.Intn(n) to get a random integer from 0 up to but not including n.
rand.Seed(seed int64): Sets the starting point for random numbers.rand.Intn(n int): Returns a random integer between 0 and n-1.
package main import ( "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) n := rand.Intn(100) // random number from 0 to 99 _ = n }
Example
This example shows how to generate and print a random number between 0 and 99. It seeds the generator with the current time to ensure different results each time you run the program.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) randomNumber := rand.Intn(100) // 0 to 99 fmt.Println("Random number:", randomNumber) }
Common Pitfalls
One common mistake is not seeding the random number generator, which causes the program to produce the same sequence of numbers every time it runs. Another is using rand.Intn() with a non-positive number, which will cause a runtime panic.
Always seed with a changing value like the current time, and ensure the argument to rand.Intn() is positive.
package main import ( "fmt" "math/rand" "time" ) func main() { // Wrong: no seed, will print the same number every run fmt.Println("No seed:", rand.Intn(100)) // Right: seed with current time rand.Seed(time.Now().UnixNano()) fmt.Println("With seed:", rand.Intn(100)) }
Quick Reference
| Function | Description |
|---|---|
| rand.Seed(seed int64) | Sets the seed for random number generation |
| rand.Intn(n int) | Returns a random integer from 0 to n-1 |
| rand.Float64() | Returns a random float64 between 0.0 and 1.0 |
| time.Now().UnixNano() | Common seed value using current time in nanoseconds |