【发布时间】:2023-03-10 21:35:01
【问题描述】:
我正在尝试实现随机时间睡眠(在 Golang 中)
r := rand.Intn(10)
time.Sleep(100 * time.Millisecond) //working
time.Sleep(r * time.Microsecond) // Not working (mismatched types int and time.Duration)
【问题讨论】:
我正在尝试实现随机时间睡眠(在 Golang 中)
r := rand.Intn(10)
time.Sleep(100 * time.Millisecond) //working
time.Sleep(r * time.Microsecond) // Not working (mismatched types int and time.Duration)
【问题讨论】:
将参数类型与time.Sleep匹配:
r := rand.Intn(10)
time.Sleep(time.Duration(r) * time.Microsecond)
这是因为 time.Duration 有 int64 作为其基础类型:
type Duration int64
【讨论】:
time.Sleep((rand.Int63n(10)) * time.Second) 我试图传入 int64,但即使这样也行不通。 @DmytroBogatov 可能是正确的。
time.Sleep(time.Duration(rand.Int63n(10))*time.Second)。 Go 中没有自动类型转换。至于我的回答还是正确的:golang.org/pkg/time/#Duration
time.Second是否是int64和rand.Int63n()也返回int64,那么为什么在乘法过程中会出现类型不匹配?
如果您尝试多次运行相同的 rand.Intn,您将在输出中看到始终相同的数字
就像官方文档中写的那样https://golang.org/pkg/math/rand/
顶级函数(例如 Float64 和 Int)使用默认共享源,每次运行程序时都会生成确定的值序列。如果每次运行需要不同的行为,请使用 Seed 函数初始化默认 Source。
它应该看起来像
rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)
【讨论】: