Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I tried:

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

but I got the following error message:

constant 18446744073709551615 overflows int

How can I fix this? Thanks!

like image 941
abw333 Avatar asked May 10 '13 03:05

abw333


People also ask

What is FMT Println in Go?

The fmt. Println function in the GO programming language is a function used to print out a formatted string to the console. fmt. Println does not support custom format specifiers, which means only the default formats are used to format the string .

What verb should we use with FMT printf to print integer?

Printf, Sprintf, and Fprintf all take a format string that specifies how to format the subsequent arguments. For example, %d (we call that a 'verb') says to print the corresponding argument, which must be an integer (or something containing an integer, such as a slice of ints) in decimal.

What does %q mean in Golang?

String and slice of bytes (treated equivalently with these verbs): %s the uninterpreted bytes of the string or slice %q a double-quoted string safely escaped with Go syntax %x base 16, lower-case, two characters per byte %X base 16, upper-case, two characters per byte.


1 Answers

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.

like image 85
Stephen Weinberg Avatar answered Oct 11 '22 09:10

Stephen Weinberg