英文:
How the big int represent in golang?
问题
这段代码是正确的,
package main
import "fmt"
const (
Big = 1 << 100
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))
fmt.Println(needFloat(Big))
}
但是当我添加
fmt.Println(Big)
时,遇到了一个错误:
tmp/sandbox042871394/main.go:16: constant 1267650600228229401496703205376 overflows int
我对下面这段代码感到困惑:
const (
Big = 1 << 100
Small = Big >> 99
)
为什么这两行代码没有出错。
英文:
this code is right,
package main
import "fmt"
const (
Big = 1 << 100
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))
fmt.Println(needFloat(Big))
}
But when i add
fmt.Println(Big)
I meet an error:
tmp/sandbox042871394/main.go:16: constant 1267650600228229401496703205376 overflows int
i am confused for
const (
Big = 1 << 100
Small = Big >> 99
)
why there is no error for this two lines code.
答案1
得分: 2
简短回答:Big是无类型整数常量。
常量表达式总是精确计算的;中间值和常量本身可能需要比语言中任何预声明类型支持的精度更大。以下是合法的声明:
const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (无类型整数常量)
const Four int8 = Huge >> 98 // Four == 4 (类型 int8)
参考文献 https://golang.org/ref/spec#Constant_expressions
在常量中,您没有明确指定它是一个整数,如果指定了,它将失败
const (
Big int = 1 << 100
Small = Big >> 99
)
将显示错误
tmp/sandbox351128854/main.go:9: constant 1267650600228229401496703205376 overflows int
英文:
Short answer : Big is untyped integer constant
Constant expressions are always evaluated exactly; intermediate values and the constants themselves may require precision significantly larger than supported by any predeclared type in the language. The following are legal declarations:
const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
const Four int8 = Huge >> 98 // Four == 4 (type int8)
reference https://golang.org/ref/spec#Constant_expressions
Here in the constant you have not explicitly said it is an integer if said it would have failed
const (
Big int = 1 << 100
Small = Big >> 99
)
will show error
tmp/sandbox351128854/main.go:9: constant 1267650600228229401496703205376 overflows int
答案2
得分: 1
大和小是未指定类型的常量。
fmt.Println
接受interface{}
。常量会被转换为其默认类型。
默认类型是int。
英文:
Big and Small are untyped constants.
fmt.Println
accepts interface{}
. Constant is converted to its default type.
The default type is int.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论