英文:
Question about operations that mix numeric types in Go
问题
我知道Go是一种静态类型语言,不允许混合使用数值类型的操作,例如,你不能将int和float64相加:
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可以工作?在直接使用它们进行加法运算时,1和1.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被评估为一个无类型的常量表达式。
因此,下面的程序也可以工作,因为现在a和b都是无类型的常量。
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论