Go Operators

operators are used to perform operations on variables and values. Here are some of the most common operators in Golang, along with examples of how to use them:

  1. Arithmetic operators:

Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, and division. Here are some examples:

package main

import "fmt"

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

    fmt.Println(a + b) // Addition
    fmt.Println(a - b) // Subtraction
    fmt.Println(a * b) // Multiplication
    fmt.Println(a / b) // Division
}
  1. Comparison operators:

Comparison operators are used to compare two values and return a boolean value of true or false. Here are some examples:

package main

import "fmt"

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

    fmt.Println(a == b) // Equal to
    fmt.Println(a != b) // Not equal to
    fmt.Println(a > b)  // Greater than
    fmt.Println(a < b)  // Less than
    fmt.Println(a >= b) // Greater than or equal to
    fmt.Println(a <= b) // Less than or equal to
}
  1. Logical operators:

Logical operators are used to combine two or more boolean expressions and return a boolean value. Here are some examples:

package main

import "fmt"

func main() {
    a := true
    b := false

    fmt.Println(a && b) // AND
    fmt.Println(a || b) // OR
    fmt.Println(!a)    // NOT
}
  1. Assignment operators:

Assignment operators are used to assign a value to a variable. Here are some examples:

package main

import "fmt"

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

    a += b // Equivalent to a = a + b
    fmt.Println(a)

    a -= b // Equivalent to a = a - b
    fmt.Println(a)

    a *= b // Equivalent to a = a * b
    fmt.Println(a)

    a /= b // Equivalent to a = a / b
    fmt.Println(a)

    a %= b // Equivalent to a = a % b
    fmt.Println(a)
}
Follow us on social media
Follow Author