In Go, you can use the math/rand
package to generate random numbers or random integers. Here's how you can do it:
import (
"fmt"
"math/rand"
"time"
)
main
function or any other function where you want to generate random numbers, seed the random generator with a unique value, such as the current time:func main() {
rand.Seed(time.Now().UnixNano())
// Rest of your code
}
Seeding ensures that each time your program runs, it generates a different sequence of random numbers.
// Random number between 0 and 99
randomNum := rand.Intn(100)
In the above example, rand.Intn(n)
generates a random integer in the range [0, n). The upper bound is exclusive, so rand.Intn(100)
will generate random numbers from 0 to 99.
// Random integer between 10 and 20
randomInt := rand.Intn(11) + 10
In this example, rand.Intn(11)
generates a random number between 0 and 10, and we add 10 to shift the range to 10-20.
fmt.Println(randomNum)
fmt.Println(randomInt)
That's it! Run your program, and you'll see different random numbers or integers each time.