Home »
Golang
Go Operator Precedence and Associativity
Last Updated : July 17, 2025
In Go, operators have a predefined precedence and associativity which determine how expressions are evaluated.
What is Operator Precedence?
Operator precedence decides which operator is evaluated first in an expression with multiple operators. For example, multiplication has higher precedence than addition.
Example
package main
import "fmt"
func main() {
result := 10 + 2 * 3
fmt.Println("Result:", result)
}
When executed, this program outputs:
Result: 16
Here, 2 * 3
is evaluated first (due to higher precedence), then 10 + 6
.
What is Associativity?
Associativity defines the direction in which operators of the same precedence are evaluated — either left-to-right or right-to-left.
Example
Assignment (=
) is right-associative:
package main
import "fmt"
func main() {
var a, b, c int
a = b = c = 5
fmt.Println(a, b, c)
}
This program will result in a compilation error because Go does not allow chained assignments like this. Unlike some other languages, Go requires individual assignment statements.
Common Operator Precedence Table
Below is a simplified table of Go operator precedence (from highest to lowest):
- Highest:
* / % << >> & &^
+ - | ^
== != < <= > >=
&&
||
- Lowest:
= += -= *= /=
(and other assignments)
Use Parentheses to Clarify
To avoid ambiguity, it's a good practice to use parentheses even when you know precedence. It improves code readability and helps prevent logic errors.
Example
package main
import "fmt"
func main() {
result := (10 + 2) * 3
fmt.Println("Result:", result)
}
Now, 10 + 2
is evaluated first due to the parentheses, so output will be:
Result: 36
Exercise
Select the correct answers based on Go operator precedence and associativity.
- Which operator has higher precedence?
- What is the associativity of the logical AND (
&&
) operator in Go?
- Which expression is correct in Go?
Advertisement
Advertisement