Home > Article > Backend Development > 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!