Pull to refresh

Comments 4

Could you please correct this fragment (following up with correspondent corrections below it)?


In our use case, however, we will be just fine with the maximum value for an int64. Any of these will do:

minLn := 1 << 63 - 1

minLn := math.MaxInt64

The first variant is incorrect — and you picked the incorrect one out of two! Worse, you formatted this bad expression later on as 1<<63 - 1 — no spaces around << to kind of stress the fact that as you think this operation has the higher precedence over -.


No it does not. You need parentheses around 1 << 63. Go has C-style precedence of operators and - is one step higher in the precedence order than <<, so your expression yields the same result as 1 << 62 which is not what you meant. Check this table, for example: https://www.tutorialspoint.com/go/go_operators_precedence.htm.


Please correct!

Hey sashagil!


Thank you for your comment and interesting observation!


While the precedence order that mentioned is correct to the vast majority of programming languages, it is not the case for Go:


There are five precedence levels for binary operators. Multiplication operators bind strongest, followed by addition operators, comparison operators, && (logical AND), and finally || (logical OR):

    5             *  /  %  <<  >>  &  &^
    4             +  -  |  ^
    3             ==  !=  <  <=  >  >=
    2             &&
    1             ||

The quote above is from Golang spec.


We can verify it in playground:


v := 1<<63 — 1
v1 := (1 << 63) — 1
fmt.Println(v == v1) // true

Good to know, thanks — looks like i was fooled by a random "tutorial" page that pops up in search results at the top.

Sign up to leave a comment.

Articles