# How to generate a random int in Golang

• 27 September 2019

In Golang there a are two libraries for generating random integers:

• `math/rand` - this package implements a pseudo-random number generator.
• `crypto/rand` - this package implements a cryptographically secure random number generator.

## math/rand

This deterministic method is useful when you want random numbers but still need to reproduce the situation.

By default, the random number generator is "seeded" with the value 1, this means it is possible to predict what random numbers will be generated.

The randomness of the method is achieved using the seed and for example, by using the current time will add complexity in predicting the values.

``````package main

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

func main() {
fmt.Println("Random Integer using math/rand")
fmt.Println()

// Uses default seed of 1, result will be 81:
number0 := rand.Intn(1000)
fmt.Println("default seed of 1: ", number0)

fmt.Println()

// Seed the random number generator using the current time (nanoseconds since epoch)
rand.Seed(time.Now().UnixNano())

// Much harder to predict...but it is still possible if you know the day, and hour, minute...
number1 := rand.Intn(1000)
fmt.Println("seed of current time: ", number1)
}
``````

### Output

``````Random Integer using math/rand

default seed of 1:  81

seed of current time:  927
``````

## crypto/rand

The will offer a cryptographically secure method of generating a random number.

``````package main

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

func main() {
fmt.Println("Random Integer using crypto/rand")
fmt.Println()

if err != nil {
panic(err)
}

fmt.Println("Random number:", number0)
}
``````

### Output

``````Random Integer using crypto/rand

Random number: 597
``````

### Compile&Run

To compile the code, navigate to the file location and run the following command.

``\$ go build randomInt.go``

Then depending on if you are on Linux or Windows the binary file is created.

To run the application, execute the command.

#### Linux

``\$ ./randomInt``

#### Windows

``c:\Users\adm\go\tutorials> randomInt.exe``

If you want to compile and run the application in one single step run the following command:

``go run randomInt.go``

Search
Other Posts