# How to Get Int31n Type Random Number in Golang?

Golang is a programming language that has gained immense popularity in recent years. One of its many features is the ability to generate random numbers of different types. In this article, we will focus on generating random Int31n type numbers in Golang.

Int31n is a type of 32-bit signed integer. It is a commonly used data type in programming and is often required for a wide range of applications. Here's how you can generate random numbers of type Int31n in Golang.

## Step 1: Import the Math/rand Package

To generate a random number in Golang, you need to import the math/rand package. This package contains functions that can be used to generate random numbers of different types.

import "math/rand"


## Step 2: Seed the Random Number Generator

Before you can generate random numbers in Golang, you need to seed the random number generator. This is done by using the Seed function from the math/rand package. The Seed function takes an int64 value as its parameter, which is used to initialize the generator.

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


The UnixNano function is used to get the current Unix time in nanoseconds. This ensures that the seed value changes every time the program is run, which makes the random numbers more unpredictable.

## Step 3: Generate the Random Number

To generate a random number of type Int31n, you can use the Int31n function from the math/rand package. This function takes a single int32 parameter n and returns a random number in the range [0, n).

randomNumber := rand.Int31n(n)


Here, n is the upper limit of the range for the random number. For example, if you want to generate a random number between 0 and 100, you would set n to 100.

## Step 4: Use the Random Number

Once you have generated a random number of type Int31n, you can use it in your program as required. For example, you can print the random number to the console using the fmt.Println function.

fmt.Println(randomNumber)


That's it! By following these simple steps, you can generate random numbers of type Int31n in Golang. Remember to always seed the random number generator to ensure that the numbers generated are truly random and unpredictable.

### Example

package main

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

func main() {
rand.Seed(time.Now().UnixNano())

// generate a random number between 0 and 100
randomNumber := rand.Int31n(101)

fmt.Println(randomNumber)
}


### Output

59


## Conclusion

Generating random numbers of type Int31n in Golang is a straightforward process that can be accomplished with just a few lines of code. By following the steps outlined in this article, you can generate random numbers of any desired range in your Golang program.

Updated on: 08-May-2023

94 Views

##### Kickstart Your Career

Get certified by completing the course