To generate a random number in Go, use the math/rand package: rand.Intn(n) returns a non-negative pseudo-random integer in [0, n), and rand.Float64() returns a pseudo-random float in [0.0, 1.0). For cryptographically secure randomness, use crypto/rand instead.
Background: The math/rand Package
Go’s standard library provides two random number packages. math/rand is a fast, deterministic pseudo-random number generator (PRNG) based on a seeded algorithm. It is ideal for simulations, games, or any use where speed matters and security is not a concern. The package has been part of Go since version 1.0, but its API changed slightly in Go 1.20: the global functions (like rand.Intn) are now automatically seeded with a random seed, so you no longer need to call rand.Seed manually. Before 1.20, the default seed was fixed, producing the same sequence every run unless you seeded it yourself.
The other package, crypto/rand, generates numbers from the operating system’s entropy source, making them unpredictable and suitable for cryptographic keys, tokens, or anything security-sensitive. It is slower and has a different API (it fills a byte slice).
How to Generate a Random Integer
The most common task is getting a random integer in a range. Here is a minimal example:
package main
import (
"fmt"
"math/rand"
)
func main() {
// Random integer from 0 to 99 (inclusive of 0, exclusive of 100)
n := rand.Intn(100)
fmt.Println(n)
}
If you need a random integer between min and max (inclusive of both), use the formula rand.Intn(max-min+1) + min. For example, a random number between 5 and 15 inclusive:
min, max := 5, 15
result := rand.Intn(max-min+1) + min
fmt.Println(result)
For a random 64-bit integer, use rand.Int63() (returns a non-negative int64) or rand.Uint64() (returns a uint64). To get a random integer from a specific range with full 64-bit precision, you might need to use rand.Int63n(n) which works like Intn but for int64.
Generating Random Floats and Other Types
To get a random float between 0.0 and 1.0, use rand.Float64(). To get a float in a custom range [a, b), use a + rand.Float64()*(b-a). Example:
// Random float between 10.0 and 20.0
f := 10.0 + rand.Float64()*10.0
fmt.Println(f)
For random bytes (useful for generating random strings), you can fill a slice using rand.Read() (which is deprecated in Go 1.20; use rand.Read from crypto/rand for secure, or use rand.Uint64() manually). A common pattern for a random string is to pick from a character set:
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, 10)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
fmt.Println(string(b))
Seeding and Reproducibility
In Go 1.20 and later, the global random source is automatically seeded with a random seed, so each run produces different numbers. However, if you need a reproducible sequence (e.g., for testing), you can create a local rand.Rand with a fixed seed:
r := rand.New(rand.NewSource(42))
fmt.Println(r.Intn(100)) // Always prints the same number
Note that rand.NewSource returns a source that is not safe for concurrent use; if you need concurrent access, use rand.New with a locked source (in Go 1.20+, rand.NewSource is actually a *rand.Rand that is safe for concurrent use, but to be safe, use a mutex or the global functions which are safe).
For cryptographic randomness, you do not seed; the OS provides entropy. Example:
import "crypto/rand"
func cryptoRandomInt(max int) (int, error) {
if max <= 0 {
return 0, fmt.Errorf("max must be positive")
}
// Use rejection sampling to avoid modulo bias
maxUint := uint(max)
var b [8]byte
for {
_, err := rand.Read(b[:])
if err != nil {
return 0, err
}
// Interpret as uint64, then take modulo, but reject values that would bias
val := uint(b[0]) | uint(b[1])<<8 | uint(b[2])<<16 | uint(b[3])<<24 |
uint(b[4])<<32 | uint(b[5])<<40 | uint(b[6])<<48 | uint(b[7])<<56
if val < ^uint(0)- (^uint(0)%maxUint) { // avoid overflow
return int(val % maxUint), nil
}
}
}
This is a simplified version; in practice, you might use crypto/rand.Int from the crypto/rand package with a big.Int for arbitrary ranges.
Choosing Between math/rand and crypto/rand
- Use
math/randwhen you need speed, reproducibility, or are building simulations, games, or any non-security-critical feature. - Use
crypto/randwhen you generate passwords, tokens, session IDs, or anything that must be unpredictable to an attacker.
For example, generating a random session token should use crypto/rand because guessing it could compromise security. A random number for a dice roll in a game can use math/rand.
Common Pitfalls and Misconceptions
One common mistake is using rand.Intn without understanding that it returns a number in [0, n), not [0, n]. So rand.Intn(6) gives 0-5, not 1-6. To simulate a die, add 1.
Another misconception is that math/rand is cryptographically secure. It is not; it is a PRNG, and its output can be predicted if the seed is known. Never use it for security.
Also, before Go 1.20, forgetting to seed the global generator produced the same sequence every time, which surprised many developers. If you are on an older version, call rand.Seed(time.Now().UnixNano()) at program start.
Finally, be aware of modulo bias: if you use rand.Intn(n) with a non-power-of-two n, the distribution is slightly biased because the underlying range (2^63) is not a multiple of n. For most applications this bias is negligible, but for cryptographic work, use crypto/rand with rejection sampling.
Performance and Concurrency
The global math/rand functions are safe for concurrent use; they use a locked source internally. However, if you have high concurrency, the lock can become a bottleneck. In that case, create a separate rand.Rand for each goroutine (with its own source) to avoid contention. Example:
// In each goroutine:
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// use r.Intn(...)
But be careful: creating a new source with the same seed in two goroutines can produce identical sequences. Use a unique seed per goroutine (e.g., include a goroutine ID or a counter).
For crypto/rand, it is safe for concurrent use and does not require locking.
Frequently Asked Questions
How do I generate a random number between 1 and 100 in Go?
Use rand.Intn(100) + 1. This gives a number from 1 to 100 inclusive because Intn(100) returns 0-99, and adding 1 shifts it to 1-100.
Why does my Go program always produce the same random numbers?
If you are using Go 1.19 or earlier, the global random source is not automatically seeded. You need to call rand.Seed(time.Now().UnixNano()) at the start of your program. In Go 1.20+, this is done automatically.
Is math/rand safe for generating passwords?
No. math/rand is a pseudo-random generator; its output is predictable if the seed is known. For passwords, tokens, or any security-sensitive data, use crypto/rand.
How can I generate a random string in Go?
Create a byte slice and fill each byte with a character from a predefined alphabet using rand.Intn(len(alphabet)). For secure random strings, use crypto/rand to fill bytes and then map them to the alphabet, but be careful to avoid modulo bias.
What is the difference between rand.Intn and rand.Int63n?
rand.Intn(n) returns an int between 0 and n-1, suitable for 32-bit or 64-bit systems. rand.Int63n(n) returns an int64 between 0 and n-1, useful when you need a 64-bit integer or when n is larger than the max int on 32-bit systems.
Can I use math/rand in a web server?
Yes, but if you need to generate session IDs or CSRF tokens, use crypto/rand. For non-security random numbers (e.g., randomizing a quiz question order), math/rand is fine.
Related
- AMORLINC in Google Sheets: Function Guide
- Random Number 1-9: How to Pick One
- How to Capitalize Everything in Excel: 4 Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Flip the Order of Cells in Excel Without Re-typingTo flip cells in Excel, add a helper column containing 1, 2, 3, and so on, select the…
- Add Color to Excel Data Validation ListsTo add color to an Excel data-validation list, create the drop-down first, then use conditional formatting to color…
- Excel Data Analysis: Where to Click and How to PracticeTo run Excel’s Analysis ToolPak on Windows, choose Data > Data Analysis, select a tool, and enter the…
- How to Turn On Track Changes in ExcelTrack Changes in Excel lets you see every edit made to a shared workbook, including who made the…
- How to Unhide Rows in Excel: Quick Steps and FixesTo open hidden rows in Excel for Microsoft 365 on Windows, select the row headers immediately above and…
- Excel Frozen Not Responding? Steps to Recover SafelyIf Excel says Not Responding, stop clicking and give it a little time: it may be calculating, opening…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.