Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed. Here, if you need different output or outcome for each execution, you can use the seed function to initialize the default source which is safe for concurrent use by multiple goroutines. It generates an integer in the interval of 0 and n. It takes only one argument, the n or the upper bound & throws error if argument is less than zero.
RandomInteger := rand.Int() // generates a random integer
RandomIntegerwithinRange: To generate the number within the range where max is the upper bound and min is the lower bound.
RandomIntegerwithinRange := rand.Intn(max-min) + min // range is min to max
rand.Float64(): It generates the floating point number between 0.0 and 1.0, It is as easy as rand.Int to use.
RandomFloatingNumber := rand.Float64() // generates a random floating point number
Example:
// Generating Random Numbers in Golang package main import ( "fmt"
"math/rand"
"time"
) func main() { // Intn returns, as an
// int, a non-negative
// pseudo-random number in
// [0,n) from the default Source.
// i.e. simply call Intn to
// get the next random integer.
fmt.Println( rand .Intn(200))
fmt.Println( rand .Intn(200))
fmt.Println( rand .Intn(200))
fmt.Println()
// Float64 returns, as
// a float64, a pseudo-random
// number in [0.0,1.0)
// from the default Source.
fmt.Println( rand .Float64())
// By default, it uses the value 1.
fmt.Println(( rand .Float64() * 8) + 7)
fmt.Println(( rand .Float64() * 8) + 7)
fmt.Println()
// Seeding - Go provides a method,
// Seed(see int64), that allows you
// to initialize this default sequence.
// Implementation is slow
// to make it faster
// rand.Seed(time.Now().UnixNano())
// is added. Seed is the current time,
// converted to int64 by UnixNano.
// Gives constantly changing numbers
x1 := rand .NewSource( time .Now().UnixNano())
y1 := rand .New(x1)
fmt.Println(y1.Intn(200))
fmt.Println(y1.Intn(200))
fmt.Println()
x2 := rand .NewSource(55)
y2 := rand .New(x2)
fmt.Println(y2.Intn(200))
fmt.Println(y2.Intn(200))
fmt.Println()
x3 := rand .NewSource(5)
y3 := rand .New(x3)
fmt.Println(y3.Intn(200))
fmt.Println(y3.Intn(200))
} |
Output:
81 87 47 0.4377141871869802 10.397099976570125 12.494584582936875 0 128 112 164 26 36
The above method is not safe if the user wants to keep the random numbers secret. That’s why Golang provides Crypto rand to varies the level of randomness of numbers to come. It is crypto-ready to use and secure but it is slower. It is used for generating passkeys, CSRF tokens or anything related to security.
Example:
package main import ( "crypto/rand"
"fmt"
) func main() { RandomCrypto, _ := rand .Prime( rand .Reader, 128)
fmt.Println(RandomCrypto)
} |
When you will execute this code, you will get different output each time.