Skip to content
Tutorials Center
My learning

Topics

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.

Go
x := a + b*c        // b*c first
ok := a < b && c    // comparison before &&

Try it

Go Grouping in action

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.

Go Short-circuiting and mixed levels

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 - c is (a - b) - c.
  • The shift operators belong to the multiplication level. So 1<<3 + 1 is 8 + 1, not 1 << 4. Parenthesize shifts when mixing them with +.
  • | and ^ (OR and XOR) sit with + and -, while & and &^ sit with *. This makes a&b == c parse as (a&b) == c, which differs from C.
  • Comparison operators are non-associative in effect: a < b < c does not compile, because a < b is a boolean that cannot be compared with a number.
  • && and || short-circuit: the right side is evaluated only if needed.
  • !a == b parses as (!a) == b, since unary ! binds first. Write !(a == b) or a != 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.