Working with Operators in Go

10.26.2021

Intro

Operators allow us to perform mathematics, comparisons, and much more in programming. Go provides a great set of operators for your daily use. In this article, we will learn how to use operators in Go.

Setting Up

Let's start be creating a new file

touch main.go

We can then add the following code.

package main

import "fmt"

func main() {
   fmt.Println("Hello!")
}

We can run the code using the following.

go run main.go

Using Operators

In this article, we will give a brief program with an example of many operators. For a full list, we can refer to the documentation: https://golang.org/ref/spec#Operators.

Go operators consist of the following categories:

  • Arithmetic
  • Relational
  • Logical
  • Bitwise
  • Assignment
  • Misc

Our program below shows examples of each, with a

package main

import "fmt"

func main() {
   // Arithmetic
   var a int = 10
   var b int = 20

   fmt.Println(a + b)
   fmt.Println(a * b)
   a++ // increment A by itself
   fmt.Println(a)


   // Relational
   fmt.Println(a == b)
   fmt.Println(a != b)
   fmt.Println(a > b)
   
   // Logical
   fmt.Println(a > b && b < a)
   fmt.Println(a < b || b == a)

   // Bitwise
   fmt.Println(a & b)
   fmt.Println(a | b)
   fmt.Println(a << 2)

   // Assignment
   a = 20
   fmt.Println(a)

   a += 20
   fmt.Println(a)
   
   // Misc
   fmt.Println(&b) // Memory Address
}