Course Content

Introduction to GoLang

## Introduction to GoLang

# Basics of Operators & Expressions

In Go programming, operators are symbols or combinations of symbols that perform various operations on values or variables.

An expression is a combination of values and operators that yield an evaluated value. For example, `7 + 9`

is an expression that yields `16`

, and `7 * 9`

is an expression that yields `63`

, as the `*`

operator represents multiplication.

In this chapter, we will explore the Arithmetic operators. Most of the remaining operators will be discussed in subsequent sections, as relevant.

Operator | Function |

`+` | Addition |

`-` | Subtraction |

`*` | Multiplication |

`/` | Division |

`%` | Remainder(Mod) |

`++` | Increment |

`--` | Decrement |

Studying the following code and its corresponding outputs can be a valuable exercise in code comprehension. All the arithmetic operators are elucidated within the code using comments, along with the respective output.

index.go

By default, in Go, expressions are evaluated using the BODMAS (also known as PEMDAS) rule. According to this rule, an expression is evaluated in the following order:

__Brackets;____Exponents;____Division;____Multiplication;____Addition;____Subtraction;__

Consider the expression `1 + 3 * 4 / 2`

. The order of evaluation and the result are as follows:

`1 + 3 * 4 / 2`

→ `1 + 3 * 2`

→ `1 + 6`

→ `7`

Hence, `fmt.Println(1 + 3 * 4 / 2)`

outputs `7`

.

We can use brackets to change the order of operations and, consequently, the result:

`(1 + 3) * 4 / 2`

→ `4 * 4 / 2`

→ `4 * 2`

→ `8`

Brackets can also be nested for more precise control of operations:

`((1 - 3) + 4) / 2`

→ `(-2 + 4) / 2`

→ `2 / 2`

→ `1`

In the above case, subtraction was performed first, followed by addition, and then division.

Everything was clear?