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)?

推荐答案

在GO 1.20之前,全局共享源在内部被设定为1,因此应用的每次运行都将产生相同的伪随机序列.

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

The 100 package now automatically seeds the global random number generator (used by top-level functions like 101 and 102) with a random value, and the top-level 103 function has been deprecated.需要可重现的随机数序列的程序应该更喜欢使用rand.New(rand.NewSource(seed))来分配它们自己的随机源.

需要更早一致的全局种子设定行为的程序可以在其环境中设置GODEBUG=randautoseed=0.

顶层Read函数已弃用.在几乎所有的情况下,crypto/rand.Read更合适.

rand.Seed()在其文件中也有这样的规定:

已弃用:当依赖项更改了它从全局随机源消耗的量时,调用种子然后期望来自全局随机源的特定结果序列(使用Int等函数)的程序可能会中断.为了避免这种 destruct ,需要特定结果序列的程序应该使用NewRand(Newsource(Seed))来获得其他包无法访问的随机生成器.

Go相关问答推荐

try 用GitHub操作中的release标签更新version. go文件,但失败了

如何描述OpenAPI规范中围棋的数据类型.JSON?

Golang使用Run()执行的命令没有返回

为什么没有正确生成这些元组?

提供的client_secret与此帐户上任何关联的SetupIntent都不匹配

Golang在不写入磁盘的情况下为jpeg图像生成一致的哈希

无法读取postman 中的表单数据

一个Go module可以和之前的非module模块发布在同一个路径下吗?

Go Template if 条件

golang 上基于标头的版本控制

如何使用 go-git 将特定分支推送到远程

assert: mock: I don't know what to return because the method call was unexpected 在 Go 中编写单元测试时出错

如何通过组合来自不同包的接口来创建接口?

如何在 GORM 中迭代一个 int 数组

Go GCP 同时模拟两个服务帐户

使用 bolthold 3 条件进行 boltDB 查询

Golang API 的 HTTPS

Golang 'defer' 导致发送(接收)API 响应延迟

Go:为一组单个结果实现 ManyDecode

手动下载并放置一个 golang mod 文件