Home >Backend Development >Golang >How to Correctly Multiply a Duration by an Integer in Go?
Multiplying Duration by Integer in Go
The question arises when attempting to introduce a random delay in a function for testing concurrent goroutines. By introducing the following line, the function is expected to take up to one second to return:
time.Sleep(rand.Int31n(1000) * time.Millisecond)
However, this approach triggers an error, indicating a mismatch between int32 and time.Duration types. The key to resolving this issue lies in converting the int32 to a time.Duration:
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
By converting the int32 value obtained from rand.Int31n(1000) to a time.Duration, the two types can be multiplied, allowing the function to sleep for a random interval of up to one second.
The above is the detailed content of How to Correctly Multiply a Duration by an Integer in Go?. For more information, please follow other related articles on the PHP Chinese website!