Skip to content

How to Generate Random Number using Golang?

GenerateRandomNumber() is a function that generates a random number of the specified length.

Parameters:

  • length: The length of the random number.

Returns:

  • int: The generated random number.
func GenerateRandomNumber(length int) int {
	// Generate a random number within the range of 10^length
	// using the math/rand package.

	// Calculate the maximum value of the range based on the length.
	maxValue := int(math.Pow10(length))

	// Generate a random number within the range using rand.Intn.
	num := rand.Intn(maxValue)

	// Return the generated random number.
	return num
}

Experience the magic of coding unfold as you execute this code!

package main

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

func GenerateRandomNumber(length int) int {
	return rand.Intn(int(math.Pow10(length)))
}

func main() {
	fmt.Println(GenerateRandomNumber(5)) // Output always random Example; 12481

	fmt.Println("Build with love by Adam Nasrudin")
}

enjoy your code!