How to multiply duration by integer?
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.
In Go, you can multiply variables of same type, so you need to have both parts of the expression the same type.
The simplest thing you can do is casting an integer to duration before multiplying, but that would violate unit semantics. What would be multiplication of duration by duration in term of units?
I'd rather convert time.Millisecond to an int64, and then multiply it by the number of milliseconds, then cast to time.Duration:
time.Duration(int64(time.Millisecond) * int64(rand.Int31n(1000)))
This way any part of the expression can be said to have a meaningful value according to its type. int64(time.Millisecond)
part is just a dimensionless value - the number of smallest units of time in the original value.
If walk a slightly simpler path:
time.Duration(rand.Int31n(1000)) * time.Millisecond
The left part of multiplication is nonsense - a value of type "time.Duration", holding something irrelevant to its type:
numberOfMilliseconds := 100
// just can't come up with a name for following:
someLHS := time.Duration(numberOfMilliseconds)
fmt.Println(someLHS)
fmt.Println(someLHS*time.Millisecond)
And it's not just semantics, there is actual functionality associated with types. This code prints:
100ns
100ms
Interestingly, the code sample here uses the simplest code, with the same misleading semantics of Duration conversion: https://golang.org/pkg/time/#Duration
seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
int32
and time.Duration
are different types. You need to convert the int32
to a time.Duration
:
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)