Home  >  Article  >  Backend Development  >  Why Can't I Multiply `time.Millisecond` by an `int` in Go?

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

DDD
DDDOriginal
2024-11-12 08:57:02549browse

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)

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)

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)

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!

Statement:
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