Random number generation is important for many tasks. These include game development, cryptography, and data analysis. Random values allow for distinct outcomes with an element of variability and unpredictability.
Go provides two packages for generating random values in the standard library: math/rand and crypto/rand. The math/rand package is mainly for mathematical operations. The crypto/rand package handles cryptographically secure operations.
The rand Packages
The math/rand package provides a flexible method for generating random numbers. It implements a variety of pseudo-random number generations. The package can generate a random number with different distributions, and use seeds to control the random sequence. It can also generate random numbers concurrently or in parallel.
The crypto/rand package implements a cryptographically secure random number generator. It includes functionality to generate random prime numbers with high probability.
Since these packages have the same name, you’ll need to use aliases if you want to use both in a single program, for example:
import (
crand "crypto/rand"
mrand "math/rand"
)
Generating Random Integers in Go
You can use the math/rand'sIntn function to generate random numbers in a range.
import (
"fmt"
"math/rand"
"time"
)func main() {
rand.Seed(time.Now().UnixNano())
// Intn generates a random integer between 0 and 100
// (not including 100)
randomInt := rand.Intn(100)
fmt.Println(randomInt)
}
This code passes the current time to the Seed function. It initializes the default random number generator for pseudo-randomness.
The Intn function of the rand package generates a random number between a specified range, in this case, 0 to 100.
Generate Random Floating-Point Numbers
You can generate random floating point numbers with the Float32 and Float64 functions. They return 32-bit and 64-bit floating point numbers respectively.
Here’s how you can generate random 64-bit floating point numbers in Go.
import (
"fmt"
"math/rand"
"time"
)func main() {
rand.Seed(time.Now().UnixNano())
// generate a random float64 between 0.0 and 1.0
randomFloat := rand.Float64()
fmt.Println(randomFloat)
}
The process of generating 32-bit floating point numbers is the same as generating random 64-bit floating point numbers.
Generating Cryptographically Secure Random Numbers in Go
You can use the Int function of the crypto/rand package to generate a cryptographically secure random number. The Int function takes in a reader instance and a maximum number for the limit.
import (
"crypto/rand"
"fmt"
"math/big"
)func main() {
// Create a big.Int with the maximum value for the desired range
max := big.NewInt(100000000)
// Generate a random big.Int
// The first argument is a reader that returns random numbers
// The second argument is the maximum value (not inclusive)
randInt, err := rand.Int(rand.Reader, max)
if err != nil {
fmt.Println("Error generating random number:", err)
return
}
fmt.Println("Random number:", randInt)
}
The max variable defines the maximum value for the random number using the NewInt function of the math/big package. The Int function returns the random integer and an error for handling.

Generating Cryptographically Secure Random Values
The crypto/rand package doesn't provide built-in functionality to generate cryptographically secure random strings. Still, you can work your way around this using the Read function.
import (
"crypto/rand"
"fmt"
)func cryptoRandom(stringChars string, valueLength int32) string {
bytesSlice := make([]byte, valueLength)
_, err := rand.Read(bytesSlice)
if err != nil {
return "There was an error reading from the byte slice"
}
for pos, value := range bytesSlice {
randomize := value % byte(len(stringChars))
bytesSlice[pos] = stringChars[randomize]
}
return string(bytesSlice)
}
func main() {
fmt.Println(cryptoRandom("Pneumonoultram" +
"icroscopicsilicovolcanoconiosis", 10))
}
The cryptoRandom function above takes in a string to generate a random string from. It also takes a length—a 32-bit integer—and returns a string.
In the cryptoRandom function, the bytesSlice variable is a slice of the required string length. The for-range loop traverses the byte slice and returns and retrieves the modulus of the elements of the slice and the length of the string in bytes. It updates the index of the byte slice with the modulo value index of the string.
Finally, the cryptoRandom function returns the string format of the byte slice.

You Can Generate UUIDs With Go
Generating random values come in handy for a wide range of use cases. If you need many random, unique values, you can use UUIDs.
UUIDs (Universally Unique Identifiers) ensure global uniqueness for identifiers. You can use them to distinguish between resources across systems while avoiding naming conflicts.
There are many packages you can use to generate UUIDs in Go. You can use the os package to call the uuid command on your operating system, resort to Google’s UUID package, or use the gouuid package to generate UUIDs.
ncG1vNJzZmivp6x7rq3KnqysnZ%2Bbe6S7zGieqGWXmrumvsCtnGaqkaOxsLmMp6ymmpWnwHA%3D