golang

Examples of Generating Random Numbers in Golang

A fundamental operation in programming is generating random numbers, and Go (Golang) has built-in packages for this purpose. In this article, we will explore the different approaches to generating the random numbers in Go using the standard library’s math/rand and crypto/rand packages. For the majority of versatile random number generation requirements, the math/rand package is adequate. However, the crypto/rand package is recommended for producing random numbers that are cryptographically secure.

Example 1: Generate a Random Number in Golang Using Math/Rand

Certainly, Go provides the math/rand package that provides a pseudo-random number generator. It is part of the standard library and allows us to generate random numbers and perform various operations on them.

package main

import (
   "fmt"
   "math/rand"
)

func main() {

   randomNumber := rand.Intn(100)
   fmt.Println(randomNumber)
}

Here, the math/rand package is imported first so that we can generate the random numbers using its functions. We create the variable called randomNumber and assign the value of a random integer using the rand.Intn(100) function. This function creates a non-negative random number that is smaller than the specified limit which, in this case, is 100. In other terms, it produces a random number that ranges from 0 to 100. Finally, we use the fmt.Println() function to print the randomly generated number to the console.

The random number is generated as displayed in the output:

On the second go, it generates a different random number as seen in the following:

Example 2: Generate a Random Number in Golang Using Crypto/Rand

However, we use the Go crypto/rand package to produce random integers that are cryptographically secure. This ensures that the generated random numbers are unpredictable and suitable for sensitive tasks like generating encryption keys, session tokens, or nonces.

import (
    "crypto/rand"
    "fmt"
    "math/big"
)

func main() {

    maxNum := big.NewInt(1000000000)

    randInt, err := rand.Int(rand.Reader, maxNum)

    if err != nil {
        fmt.Println("Random number generating error:", err)
        return
    }

    fmt.Println("Random number:", randInt)
}

Here, we call crypto/rand for secure random number generation and math/big to work with arbitrary-precision integers. Then, we call the “maxNum” variable that uses the big.NewInt() function. This variable represents the upper limit for the random number generation. Next, we use the rand.Int() function from the crypto/rand package to generate a random integer.

The “rand.Reader” provides a source of randomness, and the “maxNum” specifies the upper limit for the generated number. Then, a “randInt” variable is set up which receives the generated random integer. Any error during the generation process is stored in the “err” variable. After generating the random number, we check if there is an error during the generation process. If an error occurs, it is populated on the Go console and the program returns early.

The big random integer is shown in the following output which is secure and without error:

A separate secure random number is produced each time the same program is run which is shown in the subsequent output:

Example 3: Generate a Random Number in Golang Using the Seed() Method

Moreover, to provide the generator of random numbers with a particular seed value, we can utilize the Seed() method. However, the Seed() method is not used to generate random numbers directly but rather to initialize the underlying state of the random number generator such as in the math/rand package.

package main

import (
    "fmt"
    "math/rand"
)

func main() {

    rand.Seed(30)
    fmt.Printf("%d ", rand.Intn(100))
    fmt.Printf("%d \n", rand.Intn(100))

    rand.Seed(20)
    fmt.Printf("%d ", rand.Intn(100))
    fmt.Printf("%d \n", rand.Intn(100))

    fmt.Println()
}

Here, we begin by importing the necessary packages: “fmt” for printing and “math/rand” for generating random numbers. Then, we define the main() function where the rand.Seed() function is called with a seed value of 30. The seed value is intended to initialize the random number generator which guarantees that it produces the same set of random values each time the program executes with the same seed value.

Then, we use the rand.Intn(100) function to generate a random integer that lies in the range of 0 to 99. Note that we call the rand.Intn(100) function two times to execute, so two random numbers are generated. Next, the rand.Seed() function is called again but with the seed value of 20. Similarly, the program generates two more random numbers using rand.Intn(100) and fmt.Printf(), respectively.

Thus, the output represents the random values as follows:

Example 4: Generate Random Numbers of an Array in Golang Using RandArray()

Additionally, Go makes it possible to create an array of random numbers. To generate an array of random numbers in Go (Golang), we can create a custom function called randArray() that utilizes the math/rand package.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func randArray(arrLength int) []int {

    x := make([]int, arrLength)

    for k := 0; k <= arrLength -1; k++ {

        x[k] = rand.Intn(arrLength)
    }

    return x
}

func main() {

    rand.Seed(time.Now().UnixNano())

   arrLength:= 15
    fmt.Println(randArray(arrLength))
}

Here, we include the “fmt” and “math/rand” packages along with the additional "time" package to retrieve the current time. Then, we employ the randArray() function that takes an integer argument which is “arrLength” which represents the desired length of the array. Inside the function, a slice of integers called “x” is created using the make() function, with a length equal to arrLength.

After that, a loop is used to iterate from 0 to arrLength -1. In each iteration, the rand.Intn(arrLength) function is deployed to generate a random integer between 0 and arrLength -1. This random integer is assigned to the corresponding index in the “x” slice. Next, the current time serves to seed a generator for random numbers using rand.Seed(time.Now().UnixNano()) within the main() method. Lastly, we set the value of 15 for the “arrLength” variable which represents the acquired length of the random array.

The outcome of the previous program is displayed in the following where we can see the array of the random integers:

Example 5: Generate a Random Number in Golang Using Prem()

Furthermore, a random permutation can be created in Go by employing the Perm() function that is provided by the math/rand package. The Perm() function shuffles a slice of integers in a random order, creating a random permutation.

package main

import (
   "fmt"
   "math/rand"
)

func main() {

   permVal := rand.Perm(7)
   fmt.Println(permVal
}

Here, we begin with the main() function where the rand.Perm() function is utilized, taking 7 as its argument. This function creates a random permutation of numbers in the interval [0, n] where “n” is the parameter that is given to Perm(). In this case, it causes the 0 to 6 numerals to be randomly permuted. Finally, we assign the resulting permutation to the “permVal” variable.

The 0 to 6 numbers are created in the following output by random permutation:

Conclusion

We explored the examples of generating random numbers using the math/rand package including generating the integers, setting up the seed values for random numbers, random numbers of an array, and random permutations. In addition, we used a crypto/rand package to generate the secure random numbers.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content