好好爱自己!

golang time.Duration()的问题解疑

原文:  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.

posted @ 2017-06-29 16:06  立志做一个好的程序员  阅读(4429)  评论(0编辑  收藏  举报

不断学习创作,与自己快乐相处