Generate a Random Number in Go



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.


What is Random Number Generation

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.


Syntax

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
}


Example 1: Generating a random integer between two values

We can use the 'rand.Intn' method to generate a random integer between two specified values (inclusive).

For example,

  1. Import the fmt, math/rand, and time packages.
  2. Define a function named generateRandomNumber that takes two parameters min and max of type int.
  3. Seed the random number generator using the current time with rand.Seed(time.Now().UnixNano()).
  4. Use the rand.Intn method to generate a random integer between min and max (inclusive).
  5. Return the generated random number.
  6. In the main function, call the generateRandomNumber function with sample values and print the result.

Go Program

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)
}

Output

Random number between 1 and 10: 7