英文:
rand.Seed(SEED) is deprecated, how to use NewRand(NewSeed( ) )?
问题
我正在学习Go语言。在一个例子中,我看到了这行代码:
rand.Seed(SEED)
但是,Go语言的VSCode扩展提示我:
> rand.Seed自Go 1.20版本起已被弃用,并且自Go 1.0版本以来已有替代方法:如果程序调用Seed函数,并期望从全局随机源(使用Int等函数)获得特定序列的结果,当依赖项更改其从全局随机源中消耗的数量时,可能会导致程序出错。为避免此类问题,需要特定结果序列的程序应使用NewRand(NewSource(seed))来获取其他包无法访问的随机生成器。(SA1019)
我不明白如何使用建议中的NewRand(NewSource(seed))
。
我找到了关于NewSource的文档,链接为:https://pkg.go.dev/math/rand#NewSource
但是没有关于NewRand
函数的文档。
请问,rand.Seed(SEED)
的新推荐等效方法是什么?
英文:
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)
?
答案1
得分: 29
Go 1.20 Seed文档中有一个拼写错误。请按照最新文档和Go 1.20发布说明中的描述使用rand.New(rand.NewSource(seed))
。
创建随机源并使用源上的方法,而不是调用包函数:
r := rand.New(rand.NewSource(seed))
fmt.Println(r.Uint64())
fmt.Println(r.Uint64())
英文:
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())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论