go - 了解使用 Go Type Inferred Const 时的溢出

标签 go overflow type-inference

在 TourOfGo const 示例中,他们这样写

An untyped constant takes the type needed by its context

但是下面的程序会引发溢出:

package main

import "fmt"

const  Big  = 1 << 100 // no overflow here 
// var  Big  = 1 << 100  // overflow here 

func main() {
    fmt.Printf("big = %T",Big) // causes overflow error here
}

是不是只有const转var时才会溢出?

最佳答案

只要字面值只是一个常量(没有赋值给任何地方),它就不必具体化,所以不会有错误。编译器等待您在某处实际使用它。考虑一下:

package main

import "fmt"

const  Big  = 1 << 100 // no overflow here 
    var f float64
    f = Big
    fmt.Println(f)
}

这成功运行并打印出 2^100 的合理近似值(在 float 的精度限制内)。但是,如果您尝试将其分配给一个变量,它将被推断为一个 int(毕竟,字面量是整数),当您尝试打印出它的类型时也是如此。

关于go - 了解使用 Go Type Inferred Const 时的溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54232068/

相关文章:

python - 有没有办法在python中添加两个溢出的字节?

haskell - 是否有可能在 Haskell 98 中获得无限种类的错误?

TypeScript 无法正确推断函数的确定性返回类型

go - VS Code 去调试 : could not launch process: not an executable file

go - 即使进程结束也缓存或保留一个值

json - 在 go 中解码 JSON 结构制作空 map

使用 Sublime 3 返回 "go run: no go files listed"

html - 子元素水平溢出时,为什么忽略了父元素的右填充?

html - 如何在 div 中垂直对齐溢出 :hidden

c# - 为什么在传递命名方法时不能推断出这些类型参数?