0
0
GoHow-ToBeginner · 3 min read

How to Generate Random Number in Go: Simple Guide

In Go, you generate random numbers using the math/rand package. First, seed the random number generator with rand.Seed() using the current time, then call functions like rand.Intn() to get random integers.
📐

Syntax

To generate random numbers in Go, you use the math/rand package. You must seed the generator with rand.Seed() to get different results each run. Then, use functions like rand.Intn(n) to get a random integer from 0 up to but not including n.

  • rand.Seed(seed int64): Sets the starting point for random numbers.
  • rand.Intn(n int): Returns a random integer between 0 and n-1.
go
package main

import (
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	n := rand.Intn(100) // random number from 0 to 99
	_ = n
}
💻

Example

This example shows how to generate and print a random number between 0 and 99. It seeds the generator with the current time to ensure different results each time you run the program.

go
package main

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

func main() {
	rand.Seed(time.Now().UnixNano())
	randomNumber := rand.Intn(100) // 0 to 99
	fmt.Println("Random number:", randomNumber)
}
Output
Random number: 42
⚠️

Common Pitfalls

One common mistake is not seeding the random number generator, which causes the program to produce the same sequence of numbers every time it runs. Another is using rand.Intn() with a non-positive number, which will cause a runtime panic.

Always seed with a changing value like the current time, and ensure the argument to rand.Intn() is positive.

go
package main

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

func main() {
	// Wrong: no seed, will print the same number every run
	fmt.Println("No seed:", rand.Intn(100))

	// Right: seed with current time
	rand.Seed(time.Now().UnixNano())
	fmt.Println("With seed:", rand.Intn(100))
}
Output
No seed: 81 With seed: 42
📊

Quick Reference

FunctionDescription
rand.Seed(seed int64)Sets the seed for random number generation
rand.Intn(n int)Returns a random integer from 0 to n-1
rand.Float64()Returns a random float64 between 0.0 and 1.0
time.Now().UnixNano()Common seed value using current time in nanoseconds

Key Takeaways

Always seed the random number generator with rand.Seed() to get different results each run.
Use rand.Intn(n) to get a random integer between 0 and n-1.
Seed with time.Now().UnixNano() for a changing seed value.
Avoid calling rand.Intn() with zero or negative values to prevent runtime errors.
The math/rand package is simple and good for non-secure random numbers.