How to implement Random sleep in golang

Ravichandra picture Ravichandra · Jun 14, 2017 · Viewed 16.4k times · Source

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)

Answer

abhink picture abhink · Jun 14, 2017

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

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