How do number literals work in go

180 views
Skip to first unread message

iammadab

unread,
May 7, 2021, 6:09:59 PM5/7/21
to golang-nuts
I solved a problem on exercism that involved bit shifting.

There is a chess board with 64 squares, a grain of wheat is placed on the first square, for the second square you double the number of grains from the first (1 +1) = 2. For the third you double the previous (2 + 2) = 4. Continue this until the board is full.

The total function below is to add up all the grains on all the squares to know how many grains are on the board.

I defined grains as a uint64, shifted it and then returned the answer.

func Total() uint64 { 
  var grains uint64 = 1 
  return (grains << 64) - 1 
}

The mentor told me that is not needed. Modified the solution to look like this below
func Total() uint64 {
 return (1 << 64) - 1 
}
And it still worked!!
Which is something I was definitely not expecting. How does the compiler know the right amount of memory to allocate to the literal 1.

Thanks

Axel Wagner

unread,
May 7, 2021, 6:19:19 PM5/7/21
to iammadab, golang-nuts
Number literals are untyped constants in Go. They are represented as arbitrary precision integers.
When you use an untyped constant in an expression (for example as part of a return statement), it gets assigned a type - either the type that the expression must have (for example based on the return statement, other operands it's used with or if it's part of an argument), or its default type (int, for integer constants).
In your case, the compiler knows that the return type is a `uint64`, you use the literal in a return statement, so that's the type it assigns.

There is a pretty extensive explanation of Go constants in this blog post. I recommend reading that, it's more clear than my explanation :)

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/ceaa1baa-ca80-46e2-b6f5-2112adef17e9n%40googlegroups.com.

iammadab

unread,
May 7, 2021, 6:40:35 PM5/7/21
to golang-nuts
Thanks, going through the article now. Already making sense.
Reply all
Reply to author
Forward
0 new messages