Go Operators

In Go, operators are symbols that perform operations on variables and values. They allow you to manipulate data and perform various computations within your programs. Go supports a variety of operators, which can be classified into different categories based on their functionality. Here are the main categories of operators in Go:

  1. Arithmetic Operators:
    • +: Addition
    • -: Subtraction
    • *: Multiplication
    • /: Division
    • %: Modulus (remainder after division)
  2. Comparison Operators:
    • ==: Equal to
    • !=: Not equal to
    • <: Less than
    • <=: Less than or equal to
    • >: Greater than
    • >=: Greater than or equal to
  3. Logical Operators:
    • &&: Logical AND
    • ||: Logical OR
    • !: Logical NOT
  4. Bitwise Operators:
    • &: Bitwise AND
    • |: Bitwise OR
    • ^: Bitwise XOR (exclusive OR)
    • <<: Left shift
    • >>: Right shift
  5. Assignment Operators:
    • =: Simple assignment
    • +=: Add and assign
    • -=: Subtract and assign
    • *=: Multiply and assign
    • /=: Divide and assign
    • %=: Modulus and assign
    • <<=: Left shift and assign
    • >>=: Right shift and assign
    • &=: Bitwise AND and assign
    • |=: Bitwise OR and assign
    • ^=: Bitwise XOR and assign
  6. Other Operators:
    • .: Selector (used to access fields and methods of a struct)
    • :: Colon (used in the case statement in a switch)
    • () Parentheses (used for grouping and function calls)
    • []: Brackets (used for slicing and indexing arrays, slices, and maps)
    • {}: Braces (used to define blocks of code and composite literals)

Here’s a simple example to demonstrate the use of some operators in Go:

package main

import "fmt"

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

    // Arithmetic Operators
    fmt.Println("Addition:", a+b)
    fmt.Println("Subtraction:", a-b)
    fmt.Println("Multiplication:", a*b)
    fmt.Println("Division:", a/b)
    fmt.Println("Modulus:", a%b)

    // Comparison Operators
    fmt.Println("Equal to:", a == b)
    fmt.Println("Not equal to:", a != b)
    fmt.Println("Greater than:", a > b)
    fmt.Println("Less than or equal to:", a <= b)

    // Logical Operators
    fmt.Println("Logical AND:", a > 0 && b > 0)
    fmt.Println("Logical OR:", a > 0 || b > 0)
    fmt.Println("Logical NOT:", !(a > 0))
}

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
Equal to: false
Not equal to: true
Greater than: true
Less than or equal to: false
Logical AND: true
Logical OR: true
Logical NOT: false

These are the basic operators in Go, and understanding how they work is essential for performing computations and controlling the flow of your programs.