Trusted answers to developer questions

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

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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())
}

RELATED TAGS

golang
go
random number

CONTRIBUTOR

Shubham Singh Kshatriya
Did you find this helpful?