Home >Backend Development >Golang >Why Does 'time.Millisecond * int' Fail to Compile in Go, but 'time.Millisecond * 1000' Succeed?

Why Does 'time.Millisecond * int' Fail to Compile in Go, but 'time.Millisecond * 1000' Succeed?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 14:40:03193browse

Why Does

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.

Operator Type Checking

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.

Untyped Constants Exception

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.

Variable and Untyped Constant Mismatch

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)

Resolution

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!

Statement:
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