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)
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)
The code fails to compile with the error:
invalid operation: i * time.Millisecond (mismatched types int and time.Duration)
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)
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!