
In this article we will continue our Go Series, the previous topics are:
In this article we will see: Arrays, Operators and Conditions.
Arrays in Go are data structures that store a fixed sequence of elements of the same type. They are useful when you know in advance the exact number of elements that will be manipulated.
var a [5]intCreates an array of 5 integers, initialized with zero.
You can also initialize directly:
b := [3]string{"Go", "é", "fast"}Or let the compiler infer the size:
c := [...]float64{3.14, 2.71, 1.41}a[0] = 10
fmt.Println(a[0])for i, v := range b {
fmt.Println(i, v)
}[3]int and [4]int are different types. * Copying value: when assigning an array to another, it is copied:x := [2]int{1, 2}
y := x
y[0] = 9
fmt.Println(x) // [1 2]var array [2][3]int
array[0][1] = 42
Go offers a straightforward set of operators for manipulating values. They are divided into categories: arithmetic, relational, logical, bitwise, assignment, and special. They are used to perform common mathematical operations:
| Operator | Name | Description | Example |
|---|---|---|---|
+ |
Addition | Adds two values | x + y |
- |
Subtraction | Subtracts one value from another | x - y |
* |
Multiplication | Multiplies two values | x * y |
/ |
Division | Divides one value by another | x / y |
% |
Modulus | Returns the remainder of the division | x % y |
++ |
Increment | Increases the value of a variable by 1 | ++x |
-- |
Decrement | Decreases the value of a variable by 1 | --x |
There are also:
==, !=, >, <, >=, <=; + Assignment operators: =, +=, -=, *=, /=, %=, &=, |=, ^=, >>= and <<=;&&, || and !;&, |, ^, << and >> .Example of a mathematical expression with Golang:
package main
import "fmt"
func main(){
fmt.Println( 2 + 6 / 4 + 3 * 3 - (4 -1) ) // 9
}
go run operators.go
Go uses simple control structures for conditional decisions. The main ones are if, if-else, else if and switch.
ifif condition {
// block executed if condition is true
}Example:
x := 10
if x > 5 {
fmt.Println("Greater than 5")
}if with short statementAllows you to initialize variables inside the if.
if y := calculate(); y > 10 {
fmt.Println("Result > 10")
}y only exists inside the block.
if-elseif condition {
// true
} else {
// false
}else ifAllows multiple sequential checks:
if x < 0 {
fmt.Println("Negative")
} else if x == 0 {
fmt.Println("Zero")
} else {
fmt.Println("Positive")
}switchUsed for multiple comparisons, cleaner than multiple if-else.
switch value {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}break.switch true for boolean expressions:switch {
case x < 0:
fmt.Println("Negative")
case x == 0:
fmt.Println("Zero")
default:
fmt.Println("Positive")
}fallthroughForces the execution of the next case, even if the condition is not met:
switch x := 1; x {
case 1:
fmt.Println("One")
fallthrough
case 2:
fmt.Println("Two too")
}That’s all for today until the next topic!