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)
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)
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!