0
0
Goprogramming~5 mins

Operator precedence in Go

Choose your learning style9 modes available
Introduction
Operator precedence tells the computer which math or logic steps to do first when there are many in one line.
When you write math calculations with many operators like +, -, *, / in one line.
When you combine different logic checks like && and || in one condition.
When you want to make sure your code does things in the right order without extra parentheses.
When you read code and want to understand how the computer will solve the expression.
Syntax
Go
Go uses a fixed order of precedence for operators. For example:

* and / have higher precedence than + and -
== and != have lower precedence than arithmetic operators
&& has higher precedence than ||

Parentheses () can be used to change the order.
Operators with higher precedence are done before operators with lower precedence.
Use parentheses to make your code clearer and control the order explicitly.
Examples
Multiplication (*) happens before addition (+), so 4 * 2 = 8, then 3 + 8 = 11.
Go
result := 3 + 4 * 2
Parentheses change the order: 3 + 4 = 7 first, then 7 * 2 = 14.
Go
result := (3 + 4) * 2
&& has higher precedence than ||, so false && false = false first, then true || false = true.
Go
flag := true || false && false
Sample Program
This program shows how Go uses operator precedence to calculate expressions. It prints the results of each expression.
Go
package main

import "fmt"

func main() {
    a := 3 + 4 * 2
    b := (3 + 4) * 2
    c := true || false && false

    fmt.Println("a:", a)
    fmt.Println("b:", b)
    fmt.Println("c:", c)
}
OutputSuccess
Important Notes
Remember that multiplication and division happen before addition and subtraction.
Logical AND (&&) is done before logical OR (||).
Use parentheses to avoid confusion and make your code easier to read.
Summary
Operator precedence decides which parts of an expression are calculated first.
Multiplication and division have higher precedence than addition and subtraction.
Use parentheses to control or clarify the order of operations.