Why Does `time.Sleep(i * time.Millisecond)` Fail to Compile in Go?

DDD
Release: 2024-11-18 21:21:02
Original
775 people have browsed it

Why Does `time.Sleep(i * time.Millisecond)` Fail to Compile in Go?

time.Millisecond Confusion

In Go, when attempting to use the time.Sleep() function with a time.Duration value, it's essential to ensure that the values being multiplied are of the same type. This is illustrated in the code below:

// Compiles successfully
time.Sleep(1000 * time.Millisecond)
Copy after login

Here, the 1000 is an untyped constant, which is automatically converted to time.Duration before performing the multiplication.

However, when using an int variable instead:

var i = 1000
// Compilation error
time.Sleep(i * time.Millisecond)
Copy after login

The code fails to compile with the error:

invalid operation: i * time.Millisecond (mismatched types int and time.Duration)
Copy after login

This is because the variable i is of type int while time.Millisecond is of type time.Duration. Go requires that operands for binary operators such as * be of the same type, unless the operation involves shifts or untyped constants.

To resolve this, you can convert the int variable to time.Duration before the multiplication:

var i = 1000
time.Sleep(time.Duration(i) * time.Millisecond)
Copy after login

The above is the detailed content of Why Does `time.Sleep(i * time.Millisecond)` Fail to Compile 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