Home >Backend Development >Golang >How to Correctly Multiply a Duration by an Integer in Go?

How to Correctly Multiply a Duration by an Integer in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 04:38:24535browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn