Go: rand.Seed() has been deprecated: a solution

Go: rand.Seed() has been deprecated: a solution

The random seed generation function of the rand package has been abandoned in favor of a more efficient and reliable solution.

The random seed generation function of the rand package has been abandoned in favor of a more efficient and reliable solution.

The Seed(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.

Consequently the following approach should now be used:


package main

import (
"fmt"
"math/rand"
"time"
)

func main() {
     r := rand.New(rand.NewSource(time.Now().UnixNano()))
     randN := r.Intn(10)
     fmt.Println(randN) // Ex. 6
}

As you can see, the substantial change concerns the solution used to generate the initial seed with which various random numbers can be generated.