如何在golang中实现随机睡眠

How to implement Random sleep in golang

我正在尝试实现随机时间睡眠(在 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

文档:https://golang.org/pkg/time/#Duration

如果您多次尝试 运行 相同的 rand.Intn,您将在输出中看到相同的数字

和官方文档里写的一样https://golang.org/pkg/math/rand/

Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.

它应该看起来像

rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)