Search code examples
gorandom

Is it necessary to call rand.Seed manually?


I want to know do we have to call rand.Seed(n) manually in Go?
I have a code that looks like this:

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println(rand.Intn(100))
    fmt.Println(rand.Intn(100))
    fmt.Println(rand.Intn(100))
}

Everytime I run this code, each line prints different numbers than the others.
So do I need to call rand.Seed(n) each time before calling rand.Intn(100)?


Solution

  • Prior to Go 1.20, the global, shared Source was seeded to 1 internally, so each run of the appliation would produce the same pseudo-random sequences.

    Calling rand.Seed() is not needed starting from Go 1.20. Release notes:

    The math/rand package now automatically seeds the global random number generator (used by top-level functions like Float64 and Int) with a random value, and the top-level Seed function has been deprecated. Programs that need a reproducible sequence of random numbers should prefer to allocate their own random source, using rand.New(rand.NewSource(seed)).

    Programs that need the earlier consistent global seeding behavior can set GODEBUG=randautoseed=0 in their environment.

    The top-level Read function has been deprecated. In almost all cases, crypto/rand.Read is more appropriate.

    rand.Seed() also has this DEPRICATION in its doc:

    Deprecated: Programs that call Seed and then expect a specific sequence of results from the global random source (using functions such as Int) can be broken when a dependency changes how much it consumes from the global random source. To avoid such breakages, programs that need a specific result sequence should use NewRand(NewSource(seed)) to obtain a random generator that other packages cannot access.