2017-06-14 156 views
3

我想實現(在Golang)如何實現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

相關:[將time.Duration類型的微秒值轉換爲以毫秒爲單位的golang](https://stackoverflow.com/questions/41503758/conversion-of-time-duration-type-microseconds-value-to-milliseconds -in-golang/41503910#41503910)。 – icza

回答

13

匹配的類型參數來time.Sleep隨機時間睡覺:

time.Sleep(time.Duration(r) * time.Microsecond) 

這工作,因爲time.Durationuint64作爲其基本類型:

type Duration int64 

Docs:https://golang.org/pkg/time/#Duration