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

Mary-Kate Olsen
Release: 2024-11-11 15:50:03
Original
932 people have browsed it

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

Pitfalls of Time Duration Arithmetic in Go

In Go, the time.Time and time.Duration types are prevalent for working with time-related operations. However, there could be some confusion when dealing with integer multiplication and these types.

The following code exemplifies this confusion:

//works
time.Sleep(1000 * time.Millisecond)

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

The second code block fails to compile due to a type mismatch. While both 1000's in the code appear to be integers, this is not the case.

In Go, operators require operands of the same type, except for operators involving shifts or untyped constants. For our case, we have multiplication, which means the operands must be identical.

In the first line, 1000 is an untyped constant. When used in an operation, it is automatically converted to the type of the other operand, which in this case is time.Duration. However, in the second line, i is a declared variable of type int, which results in a type mismatch.

To resolve this issue, we need to convert i to time.Duration before performing the multiplication. Here's an example:

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

By converting i to time.Duration, the multiplication and subsequent time.Sleep call will now succeed.

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template