英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论