Operators

This lesson discusses operators supported by Go.

Introduction

A symbol that is used to perform logical or mathematical tasks is called an operator. Go provides the following built-in operators:

  • Arithmetic operators
  • Logical operators
  • Bitwise operators

Arithmetic operators

The common binary operators +, -, * and / that exist for both integers and floats in Golang are:

  • Addition operator +
  • Subtraction operator -
  • Division operator /
  • Modulus operator %
  • Multiplication operator *

The + operator also exists for strings. The / operator for integers is (floored) integral division. For example, 9/49/4 will give you 22, and 9/109/10 will give you 00. The modulus operator % is only defined for integers. For example, 9%4 gives 11.

Integer division by 0 causes the program to crash, and a run-time panic occurs (in many cases the compiler can detect this condition). Division by 0.0 with floating-point numbers gives an infinite result: +Inf.

There are shortcuts for some operations. For example, the statement:

b = b + a

can be shortened as:

b += a

The same goes for -=, *=, /= and %= .

As unary operators for integers and floats we have:

  • Increment operator ++
  • Decrement operator --

However, these operators can only be used after the number, which means: i++ is short for i+=1 which is, in turn, short for i=i+1. Similarly, i-- is short for i-=1 which is short for i=i-1.

Moreover, ++ and −−-- may only be used as statements, not expressions; so n = i++ is invalid, and subtler expressions like f(i++) or a[i]=b[i++], which are accepted in C, C++ and Java, cannot be used in Go.

No error is generated when an overflow occurs during an operation because high bits are simply discarded. Constants can be of help here. If we need integers or rational numbers of unbounded size (only limited by the available memory), we can use the math/big package from the standard library, which provides the types big.Int and big.Rat.

Logical operators

Following are logical operators present in Go:

  • Equality operator ==
  • Not-Equal operator !=
  • Less-than operator <
  • Greater-than operator >
  • Less-than equal-to operator <=
  • Greater-than equal-to operator >=

The following illustration describes how they work.

Get hands-on with 1400+ tech skills courses.