19

I am studying go just now.

I an example I've this line

rand.Seed(SEED) 

But the vscode extension about go is telling me

rand.Seed has been deprecated since Go 1.20 and an alternative has been available since Go 1.0: 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. (SA1019)

I cannot understand how to use NewRand(NewSource(seed)) as suggested.

I found doc about NewSource https://pkg.go.dev/math/rand#NewSource

But there is not doc about a NewRand function

What is the new reccomended equivalent of rand.Seed(SEED) ?

realtebo
  • 23,922
  • 37
  • 112
  • 189

1 Answers1

34

The Go 1.20 Seed documentation has a typo. Use rand.New(rand.NewSource(seed)) as described in the latest documentation and the Go 1.20 release notes.

Create the random source and use methods on the source instead of calling the package functions:

  r := rand.New(rand.NewSource(seed))
  fmt.Println(r.Uint64())
  fmt.Println(r.Uint64())
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • Ok, but how to use it? This returns a rand.Random oject, so must we use it instead of using rand.random() ? – realtebo Mar 01 '23 at 07:56
  • 1
    @realtebo Yes, call methods on the *rand.Random instead of calling the package functions. – Charlie Tumahai Mar 01 '23 at 16:11
  • 1
    It appears that the random generator will be automatically seeded at startup now - see VonC's answer here - https://stackoverflow.com/a/74077488 – SuperCabbage Mar 22 '23 at 14:24