# How to Get Intn Type Random Number in Golang?

Random number generation is a common task in programming, and Go provides a built-in package for generating random numbers of various types. In this article, we will explore how to generate a random number of type Intn in Go.

Intn is a type of signed integer that represents a random number in the range [0, n). Here's how you can generate a random number of type Intn in Go.

## Step 1: Import the Math/rand Package

The first step to generating a random number in Go is to import the math/rand package, which provides functions for generating random numbers of different types.

import "math/rand"


## Step 2: Seed the Random Number Generator

To generate a random number in Go, you need to seed the random number generator. This is done by calling the Seed function of the rand package, which takes an int64 value as a parameter. You can use the current time as the seed value to generate a different sequence of random numbers each time you run the program.

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


## Step 3: Generate the Random Number

Once you've seeded the random number generator, you can use the Intn function of the rand package to generate a random number of type Intn. The Intn function takes an int value n as a parameter and returns a random number in the range [0, n).

randomNumber := rand.Intn(100)


In this example, we are generating a random number between 0 and 99 (inclusive) by passing the value 100 as the parameter.

## Step 4: Use the Random Number

Finally, you can use the generated random number in your program as needed. For example, you can print it to the console using the fmt package.

fmt.Println(randomNumber)


That's it! By following these simple steps, you can generate a random number of type Intn in Go. 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())

randomNumber := rand.Intn(100)

fmt.Println(randomNumber)
}


### Output

81


## Conclusion

Generating a random number of type Intn in Go 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 Go program.

Updated on: 08-May-2023

33 Views 