rand.Seed(SEED) is deprecated, how to use NewRand(NewSeed( ) )?

PHPz
Release: 2024-02-15 16:00:10
forward
390 people have browsed it

rand.Seed(SEED) 已弃用,如何使用 NewRand(NewSeed( ) )?

php editor Xigua is here to share a solution with you. When we use rand.Seed(SEED) is deprecated, we can use NewRand(NewSeed()) instead . The NewSeed() function can generate a new seed, and the NewRand() function can use this new seed to generate random numbers. This approach helps us continue to use random number generation functionality without the limitations of rand.Seed(SEED) being deprecated. This way we can easily solve this problem and continue using the random number generation functionality.

Question content

I am currently learning go.

I am an example, I have this line

rand.seed(seed)
Copy after login

But the vscode extension about go told 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)
Copy after login

I can't understand how to use newrand(newsource(seed)) as suggested.

I found the documentation about newsource https://pkg.go.dev/math/rand#newsource

But there is no documentation about the newrand function

What is the new recommended rand.seed(seed) equivalent?

Solution

go 1.20 seed documentation has a spelling error. Use rand.new(rand.newsource(seed)) a> and go 1.20 Release Notes as described in the Latest Documentation

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

r := rand.New(rand.NewSource(seed))
  fmt.Println(r.Uint64())
  fmt.Println(r.Uint64())
Copy after login

The above is the detailed content of rand.Seed(SEED) is deprecated, how to use NewRand(NewSeed( ) )?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!