When working with concurrent goroutines in Go, it may be necessary to introduce random delays in function execution to facilitate testing. To achieve this, you may attempt to utilize the following code:
time.Sleep(rand.Int31n(1000) * time.Millisecond)
However, compiling this code will result in an error indicating a type mismatch between int32 and time.Duration. This is because the two types are distinct and cannot be directly multiplied.
To resolve this issue and correctly multiply a duration by an integer, you need to convert the int32 to a time.Duration type. This can be achieved using the following code:
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
By casting the int32 to a time.Duration, you create a valid expression that can be used to specify the sleep duration, effectively introducing a random delay in the function's execution.
The above is the detailed content of How to Correctly Multiply a Go `time.Duration` by an Integer?. For more information, please follow other related articles on the PHP Chinese website!