关于在Go语言中混合使用数值类型的操作的问题

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

Question about operations that mix numeric types in Go

问题

我知道Go是一种静态类型语言,不允许混合使用数值类型的操作,例如,你不能将intfloat64相加:

package main

import (
	"fmt"
)

func main() {
        var a int = 1
        var b float64 = 1.1
        fmt.Println(a + b)
}

运行这个程序会导致错误:

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

但是当我执行1 + 1.1这样的数学运算时,没有声明变量,程序会返回期望的结果2.1

package main

import (
	"fmt"
)

func main() {
        fmt.Println(1 + 1.1)
}

所以我的问题是:为什么1 + 1.1可以工作?在直接使用它们进行加法运算时,11.1的数值类型是什么?

英文:

I know that Go is a statically typed language that doesn't allow operations that mix numeric types, for example, you can't add an int to a float64:

package main

import (
	"fmt"
)

func main() {
        var a int = 1
        var b float64 = 1.1
        fmt.Println(a + b)
}

Running this program will cause an error:

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

But when I do the math 1 + 1.1 without declaring the variables, the program returns the desired result which is 2.1:

package main

import (
	"fmt"
)

func main() {
        fmt.Println(1 + 1.1)
}

So my question is: Why does 1 + 1.1 work? What's the numeric type of 1 and 1.1 when I use them directly in the addition?

答案1

得分: 0

如@Volker所提到的,这是因为1 + 1.1被评估为一个无类型的常量表达式。

因此,下面的程序也可以工作,因为现在ab都是无类型的常量。

package main

import (
    "fmt"
)

func main() {
        const a = 1
        const b = 1.1
        fmt.Println(a + b)
}
英文:

As mentioned by @Volker, this is because 1 + 1.1 is evaluated as an untyped constant expression.

So below program also works because now a and b are both untyped constant.

package main

import (
    "fmt"
)

func main() {
        const a = 1
        const b = 1.1
        fmt.Println(a + b)
}

huangapple
  • 本文由 发表于 2021年9月6日 14:23:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/69069939.html
匿名

发表评论

匿名网友

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

确定