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

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

DDD
Release: 2024-12-02 22:05:17
Original
262 people have browsed it

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

Problem: Multiplying Duration by Integer in Go

When attempting to test concurrent goroutines by introducing a random delay, the compiler throws the following error:

.\crawler.go:49: invalid operation: rand.Int31n(1000) * time.Millisecond (mismatched types int32 and time.Duration)
Copy after login

Solution: Converting Between Types

The error occurs because int32 (the return type of rand.Int31n(1000)) is incompatible with time.Duration (the type required for time.Sleep()). To resolve this issue, the integer value must be converted to a duration before being multiplied. This can be achieved using the following code:

time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
Copy after login

The above is the detailed content of How to Multiply an Integer by `time.Duration` 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template