In this tutorial, we will learn how to generate a random number in Go. We will cover the basic concept of random number generation and use the 'math/rand' package to generate random integers.
Random number generation is the process of producing a number that is unpredictable and does not follow a specific pattern. In Go, the 'math/rand' package provides various methods to generate random numbers.
The syntax to generate a random number in Go is:
import (
"fmt"
"math/rand"
"time"
)
func generateRandomNumber(min, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max-min+1) + min
}
We can use the 'rand.Intn' method to generate a random integer between two specified values (inclusive).
For example,
fmt
, math/rand
, and time
packages.generateRandomNumber
that takes two parameters min
and max
of type int
.rand.Seed(time.Now().UnixNano())
.rand.Intn
method to generate a random integer between min
and max
(inclusive).generateRandomNumber
function with sample values and print the result.package main
import (
"fmt"
"math/rand"
"time"
)
func generateRandomNumber(min, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max-min+1) + min
}
func main() {
// Generate a random integer between 1 and 10
randomNumber := generateRandomNumber(1, 10)
fmt.Printf("Random number between 1 and 10: %d\n", randomNumber)
}
Random number between 1 and 10: 7