Multiplying Duration by Integer in Go
To create a delay in a Go function, you may have attempted to utilize time.Sleep with a random duration generated using rand.Int31n. However, if you encountered an error stating that the types do not match, here's how to resolve it:
In your code, you have written:
time.Sleep(rand.Int31n(1000) * time.Millisecond)
This line attempts to multiply an int32 (returned by rand.Int31n) by a time.Duration (the time.Millisecond constant). However, these types are incompatible, leading to the error.
To rectify this, you need to convert the int32 to a time.Duration before multiplying it. Here's the corrected code:
time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
By converting the int32 to a time.Duration, you ensure that the multiplication is performed between compatible types, resolving the error. This will allow your function to pause for a random duration up to one second.
The above is the detailed content of How to Correctly Multiply a Duration by an Integer in Go's `time.Sleep()` Function?. For more information, please follow other related articles on the PHP Chinese website!