我正在尝试实现随机时间睡眠(在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 可能是正确的。 - Prateek Bhuwaniatime.Sleep(time.Duration(rand.Int63n(10))*time.Second)
。Go 语言没有自动类型转换。至于我的答案,它仍然是正确的:https://golang.org/pkg/time/#Duration - abhinktime.Second
是否为 int64
,而 rand.Int63n()
也返回 int64
,那么为什么在乘法过程中会出现类型不匹配的问题呢? - Prateek Bhuwaniarand.Seed(time.Now().UnixNano())
r := rand.Intn(100)
time.Sleep(time.Duration(r) * time.Millisecond)