Skip to main content

Command Palette

Search for a command to run...

rand.Seed() deprecated: way forward.

Updated
2 min read
rand.Seed() deprecated: way forward.
D

A Full Stack Developer with a knack for creating engaging web experiences. Currently tinkering with GO.

The rand.Seed() function has been deprecated since Go version 1.20:

Deprecated: As of Go 1.20 there is no reason to call Seed with a random value. Programs that call Seed with a known value to get a specific sequence of results should use New(NewSource(seed)) to obtain a local random generator.

Let's look at the example below:

package util 

import (
    "math/rand"
    "time"
)

func init() {
    rand.Seed(time.Now().UnixNano())
}

// RandomInt generates a random integer between min and max
func RandomInt(min, max int64) int64 {
    return min + rand.Int63n(max-min+1)
}

In the above example; The init() function will be called automatically when the package is first used. In this function, we set the seed value for the random generator by calling rand.Seed()
Normally the seed value is often set to the current time. As rand.Seed() expects an int64 as input, we convert it to unix nano before passing it to the function. (UnixNano a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. i.e int64)

But now that rand.Seed() has been deprecated (since Go version 1.20); Let's look at the below example on how we can implement the same.

package util

import (
    "math/rand"
    "time"
)

var randomSource *rand.Rand

func init() {
    randomSource = rand.New(rand.NewSource(time.Now().UnixNano()))
}

// RandomInt generates a random integer between min and max
func RandomInt(min, max int64) int64 {
    return min + randomSource.Int63n(max-min+1)
}

var randomSource *rand.Rand This line declares a package-level variable named randomSource of type *rand.Rand. This variable will hold an instance of the rand.Rand type, which is used for generating random numbers.

Here, Inside the init():
rand.New(...): Creates a new rand.Rand instance initialised with the source generated by rand.NewSource(...). This rand.Rand instance is then assigned to the randomSource variable.

And that's how you work with random numbers!

More from this blog

D

Dushyanth

18 posts