Go Reference ยท Operators
Operator precedence in Go
Reference for Go operator precedence: the five binary levels, unary operators, associativity, common surprises with shifts and bitwise operators.
Precedence decides how an expression such as a + b * c is grouped. Go keeps the table short: unary operators bind tightest, then there are five levels of binary operators, and all binary operators of equal precedence group left to right. Assignment and ++ are statements, so they are outside the table.
Because Go has far fewer levels than C, many C habits (such as expecting & to bind looser than ==) are corrected in Go. When an expression mixes more than two kinds of operators, add parentheses anyway; gofmt spacing will also hint at the grouping.
x := a + b*c // b*c first ok := a < b && c // comparison before &&
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
The table
| Precedence | Operators |
|---|---|
| 5 | * / % << >> & &^ |
| 4 | + - | ^ |
| 3 | == != < <= > >= |
| 2 | && |
| 1 | || |
Unary operators (+ - ! ^ * & <-) bind tighter than every binary operator. Selectors, indexing, calls and type assertions bind tighter still.
Usage notes
- Binary operators of the same precedence associate left to right:
a - b - cis(a - b) - c. - The shift operators belong to the multiplication level. So
1<<3 + 1is8 + 1, not1 << 4. Parenthesize shifts when mixing them with+. |and^(OR and XOR) sit with+and-, while&and&^sit with*. This makesa&b == cparse as(a&b) == c, which differs from C.- Comparison operators are non-associative in effect:
a < b < cdoes not compile, becausea < bis a boolean that cannot be compared with a number. &&and||short-circuit: the right side is evaluated only if needed.!a == bparses as(!a) == b, since unary!binds first. Write!(a == b)ora != b.- The order of evaluation of operands in an expression is only partly specified: function calls, method calls and channel operations happen in lexical left-to-right order, but the order relative to variable reads is not guaranteed. Do not rely on side effects inside a single expression.
Related
- + - * / %, Comparison, Logical operators, Bitwise operators
- << and >>, = and op=
- Tutorial: Operators