英文:
Why must I convert an integer to a float64 to type match?
问题
我一直在尝试使用Go语言,并在运行以下代码时遇到了一个(非)特性:
a := 1 //int
b := 1.0 //float64
c := a/b //应该是float64类型
当我运行这段代码时,出现了以下运行时错误:
invalid operation: a / b (mismatched types int and float64)
我以为Go语言在类型推断方面表现得相当不错。为什么我需要写成这样:
c := float64(a)/b //float64
一般来说,对于两种数字类型,c应该被推断为包含两者的最小类型。我无法将其视为一个疏忽,所以我只是想弄清楚为什么决定采用这种行为。仅仅出于可读性的考虑吗?还是我的建议会在语言中引起某种逻辑上的不一致?
英文:
I have been playing around with Go and I ran into a (non?)feature of Go while running the following code:
a := 1 //int
b := 1.0 //float64
c := a/b //should be float64
When I ran this I get the following run-time error:
invalid operation: a / b (mismatched types int and float64)
I thought GoLang was supposed to be pretty good with type inference. Why should it be necessary for me to write:
c := float64(a)/b //float64
In general, given two number types, c should be inferred to be the smallest type that contains both. I can't see this as being an oversight, so I am just trying to figure out why this behavior was decided upon. For readability reasons only? Or would my suggested behavior cause some kind of logical inconsistency in language or something?
答案1
得分: 18
这在常见问题解答中提到了:为什么Go语言不提供隐式的数值转换?
> 在C语言中,数值类型之间的自动转换虽然方便,但也会引起混淆。一个表达式何时是无符号的?值有多大?是否会溢出?结果是否可移植,与执行它的机器无关?这也会增加编译器的复杂性。
因此,你需要:
-
要么进行显式的**类型转换**:
c := float64(a)/b
-
要么使用
var float64
var a, b float64 a = 1 //float64 b = 1.0 //float64 c := a/b
英文:
This is mentioned in the FAQ: Why does Go not provide implicit numeric conversions?
> The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes. When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes?
It also complicates the compiler.
That is why you need:
-
either to do an explicit type conversion:
c := float64(a)/b
-
or to use
var float64
var a, b float64 a = 1 //float64 b = 1.0 //float64 c := a/b
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论