英文:
How to implement Random sleep in golang
问题
我正在尝试实现随机时间延迟(在Golang中)
r := rand.Intn(10)
time.Sleep(100 * time.Millisecond) // 正常工作
time.Sleep(time.Duration(r) * time.Microsecond) // 不工作(类型不匹配 int 和 time.Duration)
英文:
I am trying to implement random time sleep (in Golang)
r := rand.Intn(10)
time.Sleep(100 * time.Millisecond) //working
time.Sleep(r * time.Microsecond) // Not working (mismatched types int and time.Duration)
答案1
得分: 57
匹配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
英文:
Match the types of argument to time.Sleep
:
r := rand.Intn(10)
time.Sleep(time.Duration(r) * time.Microsecond)
This works because time.Duration
has int64
as its underlying type:
type Duration int64
答案2
得分: 6
如果你尝试多次运行相同的rand.Intn函数,你会发现输出总是相同的数字。
就像官方文档https://golang.org/pkg/math/rand/中所写的那样:
顶级函数,如Float64和Int,使用一个默认的共享Source,在每次运行程序时产生确定性的值序列。如果需要每次运行时不同的行为,请使用Seed函数初始化默认的Source。
代码应该像这样:
rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)
英文:
If you try to run same rand.Intn several times, you will see always the same number in output
Just like its written in the official docu 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.
It rather should look like
rand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论