How to generate a random int in Golang

  • 27 September 2019
  • ADM


How to generate a random int in Golang - images/logos/golang.jpg


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.


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 (

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

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


	// Seed the random number generator using the current time (nanoseconds since epoch)

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


Random Integer using math/rand

default seed of 1:  81

seed of current time:  927


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

package main

import (

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

	number0, err := rand.Int(rand.Reader, big.NewInt(1000))

	if err != nil {

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


Random Integer using crypto/rand

Random number: 597


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.


$ ./randomInt


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