Go Operators

Operators are symbols that perform operations on values. Go groups operators into several categories: arithmetic, comparison, logical, assignment, and bitwise. Each type serves a specific purpose in writing expressions and conditions.

Arithmetic Operators

Arithmetic operators perform mathematical calculations.

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33 (integer division)
%Modulo (Remainder)10 % 31
package main

import "fmt"

func main() {
    a := 10
    b := 3

    fmt.Println(a + b)  // 13
    fmt.Println(a - b)  // 7
    fmt.Println(a * b)  // 30
    fmt.Println(a / b)  // 3
    fmt.Println(a % b)  // 1
}

Comparison Operators

Comparison operators compare two values and always return a boolean: true or false.

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than7 > 3true
<Less than3 < 7true
>=Greater or equal5 >= 5true
<=Less or equal4 <= 5true
package main

import "fmt"

func main() {
    x := 10
    y := 20

    fmt.Println(x == y)  // false
    fmt.Println(x != y)  // true
    fmt.Println(x < y)   // true
    fmt.Println(x > y)   // false
}

Logical Operators

Logical operators combine multiple boolean conditions.

OperatorNameMeaningExample
&&ANDBoth must be truetrue && false → false
||ORAt least one must be truetrue || false → true
!NOTReverses the boolean value!true → false
package main

import "fmt"

func main() {
    age := 20
    hasID := true

    canEnter := age >= 18 && hasID
    fmt.Println(canEnter) // true

    isWeekend := false
    isHoliday := true
    dayOff := isWeekend || isHoliday
    fmt.Println(dayOff) // true
}

Assignment Operators

Assignment operators assign or update variable values in shorthand.

OperatorExampleSame As
=x = 5Assign 5 to x
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
package main

import "fmt"

func main() {
    total := 100
    total += 50
    fmt.Println(total) // 150

    total -= 30
    fmt.Println(total) // 120
}

Increment and Decrement

Go supports ++ and -- as statements, not expressions. They cannot be used inside a larger expression like in C or Java.

package main

import "fmt"

func main() {
    count := 0
    count++
    count++
    fmt.Println(count) // 2

    count--
    fmt.Println(count) // 1
}

Operator Precedence

When multiple operators appear in one expression, Go evaluates higher-precedence operators first.

result := 2 + 3 * 4  // 3*4 happens first → 2+12 = 14
fmt.Println(result)  // 14

result = (2 + 3) * 4 // parentheses force 2+3 first → 5*4 = 20
fmt.Println(result)  // 20

Key Points

  • Arithmetic operators do math: +, -, *, /, %
  • Comparison operators return true or false
  • Logical operators combine boolean conditions with &&, ||, !
  • Assignment shortcuts like += and -= update values in one step
  • Use parentheses to control evaluation order in complex expressions

Leave a Comment