Зміст курсу
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
package main import "fmt" func main() { // Addition fmt.Println("Addition (7 + 9):", 7+9) // Outputs 16 // Subtraction fmt.Println("Subtraction (7 - 9):", 7-9) // Outputs -2 // Multiplication fmt.Println("Multiplication (7 * 9):", 7*9) // Outputs 63 // Division fmt.Println("Division (10 / 2):", 10/2) // Outputs 5 fmt.Println("Division (7 / 9):", 7/9) // Outputs 0, reason will be explained in the next section // Remainder (Modulus) fmt.Println("Mod (10 % 2)", 10%2) // Outputs 0 fmt.Println("Mod (10 % 3)", 10%3) // Outputs 1 fmt.Println("Mod (10 % 4)", 10%4) // Outputs 2 var myVar = 1 fmt.Println("Value:", myVar) // Outputs 1 // Increment Operator (++) // Increases a variable's value by 1 myVar++ fmt.Println("Value (after ++):", myVar) // Outputs 2 // Decrement Operator (--) // Decreases a variable's value by 1 myVar-- fmt.Println("Value (after --)", myVar) // Outputs 1 }
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.
Дякуємо за ваш відгук!