为什么在golang中打印最大整数会导致编译错误?

huangapple go评论97阅读模式
英文:

Why does printing out max int cause compile error in golang?

问题

这是一个指向Go Playground的链接。

package main

import "fmt"
import "math"

func main() {
    fmt.Println("Hello, playground")
    fmt.Println(math.MaxUint32)
}

上述代码似乎引发了一个错误:

constant 4294967295 overflows int

fmt.Println 是否会自动将每个数字转换为 int 类型?

英文:

Here is a link to go playground

package main

import "fmt"
import "math"
func main() {
    fmt.Println("Hello, playground")
	fmt.Println(math.MaxUint32)
}

The above code seems to cause

constant 4294967295 overflows int

does fmt.Println convert every number to int automatically?

答案1

得分: 7

《Go编程语言规范》

常量

无类型常量具有默认类型,该类型是在需要类型化值的上下文中将常量隐式转换为的类型。无类型常量的默认类型分别为bool、rune、int、float64、complex128或string,具体取决于它是布尔、符文、整数、浮点数、复数还是字符串常量。

func Println(a ...interface{}) (n int, err error)

fmt.Println(math.MaxUint32)

在这个上下文中,math.MaxUint32 是一个无类型整数常量,默认为 int 类型,作为 interface{} 类型参数的无类型整数常量参数。

int 是一个带符号的32位或64位整数,具体取决于实现。

const (
    MaxInt32  = 1<<31 - 1
    MaxUint32 = 1<<32 - 1
)

MaxUint32 大于 MaxInt32

如果你运行 go env,你应该看到你正在使用一个32位的架构,例如 GOARCH="386"

不要接受默认的32位 int 类型。使用兼容的类型转换。例如,写成

fmt.Println(uint32(math.MaxUint32))
英文:

> The Go Programming Language Specification
>
> Constants
>
> An untyped constant has a default type which is the type to which the
> constant is implicitly converted in contexts where a typed value is
> required. The default type of an untyped constant is bool, rune, int,
> float64, complex128 or string respectively, depending on whether it is
> a boolean, rune, integer, floating-point, complex, or string constant.

func Println(a ...interface{}) (n int, err error)

fmt.Println(math.MaxUint32)

math.MaxUint32 is an untyped integer constant that defaults to type int in this context, an untyped integer constant argument for a type interface{} parameter.

int is a signed 32- or 64-bit integer depending on the implementation.

const (
    MaxInt32  = 1&lt;&lt;31 - 1
    MaxUint32 = 1&lt;&lt;32 - 1
)

MaxUint32 is greater than MaxInt32.

if you run go env you should see that you are using a 32-bit architecture, for example, GOARCH=&quot;386&quot;.

Don't accept the default 32-bit int type. Use a compatible type conversion. For example, write

fmt.Println(uint32(math.MaxUint32))

huangapple
  • 本文由 发表于 2016年3月26日 10:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/36231049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定