原文: How to multiply duration by integer?
看到golang项目中的一段代码,
--------------------------------------------------------------------------------------------------
You have to cast it to a correct format Playground.
yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)
If you will check documentation for sleep, you see that it requires func Sleep(d Duration)
duration as a parameter. Your rand.Int31n returns int32
.
The line from the example works (time.Sleep(100 * time.Millisecond)
) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.
有疑问加站长微信联系(非本文作者)