What is the rand.Seed() function in Golang?

In Golang, the rand.Seed() function is used to set a seed value to generate pseudo-random numbers.

If the same seed value is used in every execution, then the same set of pseudo-random numbers is generated. In order to get a different set of pseudo-random numbers, we need to update the seed value.

Syntax

rand.Seed(value)

Parameters

The rand.Seed() function accepts the following parameter:

  • value : This is the value that is set as the seed value.

Example

The code given below will show us how to use the rand.Seed()function to set the seed value:

package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
// seed to get different result every time
rand.Seed(time.Now().UnixNano())
fmt.Println(rand.Intn(50))
fmt.Println(rand.Float64())
}

Free Resources