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

How to Correctly Multiply a Go `time.Duration` by an Integer?

Mary-Kate Olsen
Release: 2024-12-05 17:55:11
Original
321 people have browsed it

How to Correctly Multiply a Go `time.Duration` by an Integer?

Multiplying Duration by Integer in Go

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

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

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!

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