二元运算符 – 操作数类型应该相同吗?

huangapple go评论76阅读模式
英文:

Binary operators - Operand types supposed to be identical?

问题

在下面的代码中:

package main

import "fmt"

func main() {

    a := 1e6
    b := 2
    fmt.Println(b / a) 
    fmt.Println(2 / a) 
}

为什么 2/a 是有效的语法?

为什么 b/a 是无效的语法?

英文:

In the below code:

package main

import "fmt"

func main() {

	a := 1e6
	b := 2
	fmt.Println(b / a) 
	fmt.Println(2 / a) 
}

why 2/a is valid syntax?

Why b/a is an invalid syntax?

答案1

得分: 3

为什么2/a是有效的语法?

"对于其他二元运算符,操作数的类型必须相同,除非操作涉及移位或无类型常量。" 2是一个无类型常量。

为什么b/a是无效的语法?

它并不是无效的。从语法上来说,它是完全有效的;只是在语义上是错误的,因为它是对不匹配类型的操作。

英文:

> why 2/a is valid syntax?

"For other binary operators, the operand types must be identical unless the operation involves shifts or untyped constants.". 2 is an untyped constant.

> Why b/a is an invalid syntax?

It isn't. It's syntactically perfectly valid; it's just semantically wrong because it's an operation on mismatched types.

答案2

得分: 2

这不是无效的语法,而是类型不匹配:

invalid operation: b / a (mismatched types int and float64)

对于二元操作,类型必须相同。
b 是一个 int,而 a 是一个 float64,所以要执行操作,你必须明确指定类型:

float64(b)/a

这将使两个操作数都变为 float64。同样可以使用以下方式:

b/int(a)

其中两个操作数都是 int

对于 2/a,这不是一个问题,因为 2 是一个无类型常量,它的实际类型是根据上下文确定的。由于 afloat64,在这种情况下 2 是一个 float64

英文:

It is not invalid syntax. It is mismatched types:

invalid operation: b / a (mismatched types int and float64)

For binary operations, types must be identical.
b is an int, and a is a float64, so to perform an operation, you have to be explicit about the types:

float64(b)/a

This would make both operands float64. So would:

b/int(a)

where both operands are int.

This is not a problem for 2/a because 2 is an untyped constant, and its actual type is determined based on context. Since a is float64, in this case 2 is a float64.

答案3

得分: 2

其他答案提供了很好的观点,我只想补充一下我记住规则的方式。首先是这个例子:

a := 1e6
b := 2
fmt.Println(b / a) 

在这个例子中,两个值都是“类型锁定”的,也就是说,在声明每个变量的类型之后进行除法运算。由于类型不匹配,操作失败:

invalid operation: b / a (mismatched types int and float64)

这个例子:

a := 1e6
fmt.Println(2 / a) 

现在2没有被分配一个类型,所以它可以是任何数值类型。由于afloat64,那么2就是“好的,我也将是float64”,除法成功。

英文:

Other answers offer good points, I just wanted to add how I remember the rules. First this example:

a := 1e6
b := 2
fmt.Println(b / a) 

With this example, both values are "type locked", that is to say, you're performing the division after declaring a type for each variable. Since the types don't match, the operation fails:

invalid operation: b / a (mismatched types int and float64)

This example:

a := 1e6
fmt.Println(2 / a) 

Now 2 has not be assigned a type, so it can essentially be any numerical type. Since a is float64, then 2 just says "OK I will be float64 too", and the division is successful.

huangapple
  • 本文由 发表于 2021年7月8日 04:41:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/68292766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定