Why Can't I Multiply `time.Millisecond` by an `int` in Go?

DDD
Release: 2024-11-12 08:57:02
Original
557 people have browsed it

Why Can't I Multiply `time.Millisecond` by an `int` in Go?

Confusion with time.Millisecond * int

In Go, operators require operands of identical types unless the operation involves shifts or untyped constants. Otherwise, if one operand is an untyped constant (e.g., an integer literal), it is converted to the type of the other operand.

Consider the following examples:

// Works because 1000 is an untyped constant and is converted to `time.Duration`.
time.Sleep(1000 * time.Millisecond)
Copy after login

However, the following code fails:

// Fails because `v` is an `int` and `time.Duration` are different types.
var v = 1000
time.Sleep(v * time.Millisecond)
Copy after login

To resolve this issue, convert the int variable v to time.Duration before using it in the Sleep function:

time.Sleep(time.Duration(v) * time.Millisecond)
Copy after login

This conversion makes the operand types identical, allowing the operation to succeed.

The above is the detailed content of Why Can't I Multiply `time.Millisecond` by an `int` 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