Apply operator precedence
Apply operator precedence
Precedence determines how an expression groups. Unary operators bind most tightly. Binary levels from highest to lowest are * / % << >> & &^, then + - | ^, then comparisons, then &&, then ||. Equal-precedence binary operators associate left to right. Parentheses make intended grouping explicit.
package main
import "fmt"
func main() { fmt.Println(2 + 3*4) fmt.Println((2 + 3) * 4) fmt.Println(20 / 5 / 2)}Multiplication groups before addition. Parentheses change the grouping in the second expression. The last expression groups as (20/5)/2.
Mix comparisons with logic
package main
import "fmt"
func main() { member := false age := 20 invited := true fmt.Println(member && age >= 18 || invited) fmt.Println(member && (age >= 18 || invited))}Comparisons bind before &&, and && before ||. The first expression accepts an invitation independently; the second requires membership. Use parentheses for clarity. Precedence controls grouping, not a general guarantee of evaluation order of every operand. Bit operators listed above are introduced later in this chapter.
Try it locally
Calculate the cost of 3 items priced at 8 each plus a shipping fee of 5. Then print (3+5)*8 to contrast grouping. Expected: 29 64.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 04: Apply operator precedence
Check the lesson objective before moving on.
What is 2 + 3 * 4?
How does 12 / 3 / 2 group?