Home > Backend Development > Golang > How to Correctly Multiply a Duration by an Integer in Go's `time.Sleep()` Function?

How to Correctly Multiply a Duration by an Integer in Go's `time.Sleep()` Function?

Mary-Kate Olsen
Release: 2024-12-05 07:21:11
Original
737 people have browsed it

How to Correctly Multiply a Duration by an Integer in Go's `time.Sleep()` Function?

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

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

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!

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