如何在golang中实现随机睡眠

Rav*_*dra 16 random time sleep go

我正在尝试实现随机时间睡眠(在Golang中)

r := rand.Intn(10)
time.Sleep(100 * time.Millisecond)  //working 
time.Sleep(r * time.Microsecond)    // Not working (mismatched types int and time.Duration)
Run Code Online (Sandbox Code Playgroud)

abh*_*ink 32

将参数类型与以下内容匹配time.Sleep:

time.Sleep(time.Duration(r) * time.Microsecond)
Run Code Online (Sandbox Code Playgroud)

这工作,因为time.Durationint64它的基本类型:

type Duration int64
Run Code Online (Sandbox Code Playgroud)

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


mat*_*son 8

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

就像官方文档中写的那样https://golang.org/pkg/math/rand/

顶级函数(例如 Float64 和 Int)使用默认共享 Source,每次运行程序时都会生成确定性的值序列。如果每次运行需要不同的行为,请使用种子函数初始化默认源。

它应该看起来像

rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)
Run Code Online (Sandbox Code Playgroud)