go - 为什么必须将整数转换为 float64 才能进行类型匹配?

标签 go

我一直在玩 Go,在运行以下代码时遇到了 Go 的一个(非?)特性:

a := 1     //int
b := 1.0   //float64

c := a/b   //should be float64

当我运行它时,出现以下运行时错误:

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

我认为 GoLang 应该非常擅长类型推断。为什么我必须写:

c := float64(a)/b    //float64

一般来说,给定两种数字类型,c 应该被推断为包含这两种类型的最小类型。我不认为这是一种疏忽,所以我只是想弄清楚为什么会做出这种行为。仅出于可读性原因?或者我建议的行为会导致语言或其他方面的某种逻辑不一致吗?

最佳答案

常见问题解答中提到了这一点: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.

这就是为什么你需要:

  • 要么做一个明确的 type conversion :

    c := float64(a)/b
    
  • 或使用 var float64

    var a, b float64
    a = 1     //float64
    b = 1.0   //float64
    c := a/b 
    

关于go - 为什么必须将整数转换为 float64 才能进行类型匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31353522/

相关文章:

build - "no godep, using go get instead"即使我运行了 "go get github.com/tools/godep"

C 回调和非 Go 线程

colors - 理解 Go 标准库中的一些魔法

arrays - 避免在输入中使用空格

go - Go编程语言中的 slice 和多重赋值

string - 如何从字符串中删除二进制内容?

go - 在单独的方法中使用golang的defer

用于多个包的 Go 模块,新的主要编号 >1

go - 不能使用 nil 作为类型模型。返回参数中的文章

mysql - Go 中的 ORM/ORM 类库