gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:26:03 25 4
gpt4 key购买 nike

我一直在玩 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com