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
Release: 2024-12-17 04:38:24
Original
539 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template