golang随机time.Sleep出现的问题

问题 最近需要使用 rand 包随机 time.Sleep() 的时间, 我的代码是这样的: 1 2 3 4 5 6 7 8 9 10 11 12 package main import ( "math/rand" "time" ) func main() { rand.Seed(time.Now().UTC().UnixNano()) n := rand.Intn(10) time.Sleep(n * time.Second) } 会遇到下面的问题: 1 2 Cannot use 'n * time.Second' (type int) as the type Duration Invalid operation: n * time.Second (mismatched types int and Duration) 解决的方法 使用 time.Duration 转换类型,代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 package main import ( "math/rand" "time" ) func main() { rand....

October 15, 2021 · 1 min · overstarry