我如何使用fmt在Go中打印出一个常量uint64?

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

How can I print out an constant uint64 in Go using fmt?

问题

我尝试了:

> fmt.Printf("%d", math.MaxUint64)

但是我得到了以下错误信息:

> 常量 18446744073709551615 溢出 int

我该如何修复这个问题?谢谢!

英文:

I tried:

> fmt.Printf("%d", math.MaxUint64)

but I got the following error message:

> constant 18446744073709551615 overflows int

How can I fix this? Thanks!

答案1

得分: 54

math.MaxUint64是一个常量,不是int64类型。请尝试使用以下代码:

fmt.Printf("%d", uint64(num))

问题在于该常量是无类型的。常量的类型取决于它在使用的上下文中。在这种情况下,它被用作interface{},因此编译器无法知道您想要使用的具体类型。对于整数常量,默认为int类型。由于您的常量溢出了int,这是一个编译时错误。通过传递uint64(num),您告诉编译器您希望将该值视为uint64类型。

请注意,这个特定的常量只适用于uint64和有时uint类型。该值甚至大于标准int64类型可以容纳的范围。

英文:

math.MaxUint64 is a constant, not an int64. Try instead:

fmt.Printf("%d", uint64(num))

The issue here is that the constant is untyped. The constant will assume a type depending on the context in which it is used. In this case, it is being used as an interface{} so the compiler has no way of knowing what concrete type you want to use. For integer constants, it defaults to int. Since your constant overflows an int, this is a compile time error. By passing uint64(num), you are informing the compiler you want the value treated as a uint64.

Note that this particular constant will only fit in a uint64 and sometimes a uint. The value is even larger than a standard int64 can hold.

huangapple
  • 本文由 发表于 2013年5月10日 11:12:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/16474594.html
匿名

发表评论

匿名网友

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

确定