How to Generate Random Number in Go

Sheeraz Gul Feb 02, 2024
  1. Random Number Generation in Go
  2. Generate Random Numbers Between a Specific Range
  3. Generate an Array of Random Numbers
  4. Seed Before Generating the Random Numbers
  5. Use Rand to Generate Random Strings
How to Generate Random Number in Go

This tutorial demonstrates how to use random number generation functionality in GoLang.

Random Number Generation in Go

GoLang provides built-in support for random number generation functionality. The built-in package math has the method rand(), which is used for random number generation.

The math/rand method generates pseudo-random numbers. The rand() method can generate a random number between the interval of 0 and n.

The syntax for this method is:

RandomNumber := rand.Intn()

The Intn() method specifies the integer value of n. Let’s try an example:

package main

import (
	"fmt"
	"math/rand"
)

func main() {

	// Generating numbers between `0 <= n < 100`.
	fmt.Print(rand.Intn(100), "\n")
	fmt.Print(rand.Intn(100), "\n")
	fmt.Print(rand.Intn(100), "\n")
	fmt.Print(rand.Intn(100), "\n")
	fmt.Print(rand.Intn(100))
	fmt.Println()

}

The code above will generate random numbers between 0 and 100. See the output:

81
87
47
59
81

Generate Random Numbers Between a Specific Range

The rand.Intn() will generate a random number between 0 and the given number, but what if we want to produce a random number between the specified range? A similar method can generate a random number between a specific range with a simple maths operation.

See the example:

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	minrange := 20
	maxrange := 45
	fmt.Println(rand.Intn(maxrange-minrange)+minrange, "\n")
	fmt.Println(rand.Intn(maxrange-minrange)+minrange, "\n")
	fmt.Println(rand.Intn(maxrange-minrange)+minrange, "\n")
	fmt.Println(rand.Intn(maxrange-minrange)+minrange, "\n")
	fmt.Println(rand.Intn(maxrange-minrange) + minrange)

}

The code above will generate random numbers between 20 and 45. See the output:

26

32

42

29

26

Program exited.

Generate an Array of Random Numbers

Similarly, we can generate an array of random numbers using the rand() method. We only have to use the for loop to generate the numbers and put them into an array.

See the example:

package main

import (
	"fmt"
	"math/rand"
)

func RandomArray(ArrayLength int) []int {

	arr := make([]int, ArrayLength)

	for i := 0; i <= ArrayLength-1; i++ {

		arr[i] = rand.Intn(ArrayLength)
	}

	return arr
}

func main() {

	ArrayLength := 15
	fmt.Println(RandomArray(ArrayLength))
}

The code above will generate an array of random numbers with a length of 15. See the output:

[11 12 2 14 1 3 10 5 1 0 14 1 12 14 13]

Program exited.

Seed Before Generating the Random Numbers

The seed() method is used to specify from where to start generating the random number because the rand() method will generate the numbers by performing some operation on the previous value.

This is the most important part of generating the random number to provide a seed close to an actual random number. Let’s try an example:

package main

import (
	"fmt"
	"math/rand"
)

func main() {

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

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

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

	fmt.Println()
}

The code above seeds the rand method with the same value three times. Then, the random number generator will generate the same number every time it finds the same seed value.

See the output:

138 16 41
138 16 41
138 16 41

Program exited.

Use Rand to Generate Random Strings

We can generate random strings using the rand method with the help of bytes. We also need the help of the method which generates a number between a specific range.

Let’s try an example:

package main

import (
	"fmt"
	"math/rand"
)

func GenerateRandomString(StringLength int) string {

	StringBytes := make([]byte, StringLength)

	for i := 0; i < StringLength; i++ {
		StringBytes[i] = byte(RandNumberinRange(65, 122))
	}

	return string(StringBytes)
}

func RandNumberinRange(minnumber int, maxnumber int) int {

	return minnumber + rand.Intn(maxnumber-minnumber)
}

func main() {
	fmt.Println(GenerateRandomString(25))
}

The code above will generate random strings using the ASCII code between 65 to 122, which includes uppercase letters, lowercase letters, and a few symbols. It will generate a string with a length of 25.

See the output:

FbpXH\fgTAvxtUxCbvLXXVOle

We can also print a random character from the given string or element. Let’s see an example:

package main

import (
	"fmt"
	"math/rand"
)

func main() {

	DemoRune := []rune("DELFTSTACK")

	Result := DemoRune[rand.Intn(len(DemoRune))]

	fmt.Println(string(Result))
}

The Rune is a data type that is used to store the code, which is used to represent the Unicode characters. The code above will print a random character from the given string.

See the output:

E

Program exited.
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook