为什么我必须将整数转换为float64以进行类型匹配?

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

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 
    

huangapple
  • 本文由 发表于 2015年7月11日 12:45:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/31353522.html
匿名

发表评论

匿名网友

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

确定