gpt4 book ai didi

go - 为什么一个 float64 类型的数字在 Go 中抛出 int 相关的错误

转载 作者:IT王子 更新时间:2023-10-29 02:28:16 25 4
gpt4 key购买 nike

我试图掌握 Golang,在教程示例之一中它说 一个无类型常量采用其上下文所需的类型。

package main

import "fmt"

const (
// Create a huge number by shifting a 1 bit left 100 places.
// In other words, the binary number that is 1 followed by 100 zeroes.
Big = 1 << 100
// Shift it right again 99 places, so we end up with 1<<1, or 2.
Small = Big >> 99
)

func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
return x * 0.1
}

func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))

// Here Big is too large of a number but can be handled as a float64.
// No compilation error is thrown here.
fmt.Println(needFloat(Big))

// The below line throws the following compilation error
// constant 1267650600228229401496703205376 overflows int
fmt.Println(Big)
}

当调用 fmt.Println(Big) 时,为什么 Golang 将 Big 视为 int 而根据上下文它应该是 float64

我错过了什么?

最佳答案

fmt.Println 的上下文是什么?换句话说,fmt.Println 期望 Big 是什么? 接口(interface){}

来自 the Go Blog on Constants :

What happens when fmt.Printf is called with an untyped constant is that an interface value is created to pass as an argument, and the concrete type stored for that argument is the default type of the constant.

所以常量的默认类型必须是int。该页面继续讨论如何根据语法而不一定是 const 的值来确定默认值。

关于go - 为什么一个 float64 类型的数字在 Go 中抛出 int 相关的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487258/

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