Home >Backend Development >Golang >Why Does 'time.Millisecond * int' Fail to Compile in Go, but 'time.Millisecond * 1000' Succeed?
Understanding "time.Millisecond * int" Mismatch in Go
In the provided code snippets, both expressions involve the multiplication operator "*" and utilize the time.Millisecond value. However, there is a discrepancy between the compilation success of these expressions. To understand this, let's delve into the fundamentals of operator usage in Go.
Go enforces strict type checking for operators, requiring the operands to be of identical types. If the operands differ in type, unless the operation involves shifts or untyped constants, the compiler will raise an error.
In the first code block, the first operand 1000 is an untyped constant. When an untyped constant is used in an operation involving only constants, it is implicitly converted to the type of the other operand. In this case, time.Millisecond is of type time.Duration, resulting in a successful conversion.
In the second code block, the first operand i is a variable of type int. When a variable and an untyped constant are involved in an operation, the type checking rules do not allow implicit conversion. Hence, the compiler flags an error: invalid operation: i * time.Millisecond (mismatched types int and time.Duration)
To resolve this issue, the i variable can be explicitly converted to time.Duration using the time.Duration(i) function, as demonstrated in the following code:
var i = 1000 time.Sleep(time.Duration(i) * time.Millisecond)
This conversion ensures that the operands are of the same type, satisfying Go's type checking requirements and allowing the code to compile successfully.
The above is the detailed content of Why Does 'time.Millisecond * int' Fail to Compile in Go, but 'time.Millisecond * 1000' Succeed?. For more information, please follow other related articles on the PHP Chinese website!