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

1

32

I tried:

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

but I got the following error message:

constant 18446744073709551615 overflows int

How can I fix this? Thanks!

Seitz answered 10/5, 2013 at 3:12 Comment(0)
L
57

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.

Lialiabilities answered 10/5, 2013 at 4:8 Comment(4)
In which respect is an uint64 bigger than an int64? I would assume "bigger" to refer to the bit size, which is the same for both type, hence the 64 suffix. Maybe you wanted to refer to the value range instead? But the range is also the same for both types, it's just that the ranges start and end at different values.Imperceptive
It is not the most precise language, but "it" is the constant and the value of the constant is "bigger" than an int64 can hold. I edited the sentence for clarity.Lialiabilities
How to print numbers that go beyond uint64, lets say I have const Big = 1 << 100, I'm getting an error cannot convert Big (untyped int constant 1267650600228229401496703205376) to type uint64Bismuth
The math/big package in the standard library has an Int type. You can use the SetString method to set any number you want. You can't define it as a constant though.Lialiabilities

© 2022 - 2024 — McMap. All rights reserved.