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)
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
If you try to run same rand.Intn several times, you will see always the same number in output
Just like its written in the official docu https://golang.org/pkg/math/rand/
Top-level functions, such as Float64 and Int, use a default shared Source that produces a deterministic sequence of values each time a program is run. Use the Seed function to initialize the default Source if different behavior is required for each run.
It rather should look like
rand.Seed(time.Now().UnixNano()) r := rand.Intn(100) time.Sleep(time.Duration(r) * time.Millisecond)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With