登录
首页 >  Golang >  Go问答

如何在Go语言中使用NewSeed()替代已弃用的rand.Seed(SEED)方法?

来源:stackoverflow

时间:2024-02-09 23:18:25 387浏览 收藏

本篇文章给大家分享《如何在Go语言中使用NewSeed()替代已弃用的rand.Seed(SEED)方法?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我现在正在学习go。

我是一个例子,我有这行

rand.seed(seed)

但是关于 go 的 vscode 扩展告诉了我

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)

我无法理解如何按照建议使用 newrand(newsource(seed))

我找到了有关 newsource 的文档 https://pkg.go.dev/math/rand#newsource

但是没有关于 newrand 函数的文档

新推荐的 rand.seed(seed) 等效项是什么?


正确答案


go 1.20 种子文档有一个拼写错误。按照最新文档中的说明使用 rand.new(rand.newsource(seed)) a> 和 go 1.20 发行说明

创建随机源并使用源上的方法而不是调用包函数:

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

好了,本文到此结束,带大家了解了《如何在Go语言中使用NewSeed()替代已弃用的rand.Seed(SEED)方法?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>