</>
Skip to content
Go lessons (9/34)

Go — Operators

Arithmetic operators

package main

import "fmt"

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

    fmt.Println("Add:", a+b)   // 13
    fmt.Println("Sub:", a-b)   // 7
    fmt.Println("Mul:", a*b)   // 30
    fmt.Println("Div:", a/b)   // 3 (integer division)
    fmt.Println("Mod:", a%b)   // 1
}

Increment and decrement

x := 5
x++ // 6
x-- // 5

Comparison operators

fmt.Println(5 == 5)  // true
fmt.Println(5 != 3)  // true
fmt.Println(5 > 3)   // true
fmt.Println(5 < 3)   // false
fmt.Println(5 >= 5)  // true
fmt.Println(5 <= 3)  // false

Logical operators

a, b := true, false

fmt.Println(a && b)  // false (AND)
fmt.Println(a || b)  // true  (OR)
fmt.Println(!a)      // false (NOT)

Bitwise operators

a, b := 0b1010, 0b1100 // 10, 12

fmt.Printf("AND: %b\n", a&b)   // 1000 (8)
fmt.Printf("OR:  %b\n", a|b)   // 1110 (14)
fmt.Printf("XOR: %b\n", a^b)   // 0110 (6)
fmt.Printf("NOT: %b\n", ^a)     // ...
fmt.Printf("Left:  %b\n", a<<1) // 10100 (20)
fmt.Printf("Right: %b\n", a>>1) // 101 (5)

Assignment operators

x := 10
x += 5   // 15
x -= 3   // 12
x *= 2   // 24
x /= 4   // 6
x %= 4   // 2

Address and dereference

x := 10
p := &x    // Address of x
fmt.Println(*p) // 10 (dereference)
*p = 20    // Modify x through pointer
fmt.Println(x)  // 20

Channel operators

ch := make(chan int, 1)

// Send
ch <- 42

// Receive
value := <-ch

// Close
close(ch)

Type assertion

var i interface{} = "hello"

// Type assertion
s, ok := i.(string)
fmt.Println(s, ok) // hello true

// Type switch
switch v := i.(type) {
case int:
    fmt.Println("int:", v)
case string:
    fmt.Println("string:", v)
}

Operator precedence

PrecedenceOperators
5*, /, %, <<, >>, &, &^
4+, -, |, ^
3==, !=, <, <=, >, >=
2&&
1||

Mini Practice

Write Go code that:

  1. Demonstrates all arithmetic operators
  2. Uses bitwise operators for flags
  3. Shows pointer address and dereference
  4. Uses a channel with send and receive operators

Up Next

In the next lesson, you'll learn about Strings — working with text in Go.

Related Topics

Frequently Asked Questions about Operators

What is Operators in Go?

Operators is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Operators?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Operators.

Why is Operators important in Go?

Operators is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.