In this Go Programming tutorial we will cover about iterations in Go Lang. Iteration or looping is a mechanism to execute certain code repeatedly. In Go, the iteration can be done using for
that can be customized based on a certain cases.
Iteration with for
This is the basic syntax to create an iteration or loop using for.
for {
// code..
// define the condition when the iteration is stopped
}
|
In this example, the iteration or loop with for is used to print out the number from 1 until 5.
package main
import "fmt"
func main() {
// create a num variable
var num int32 = 1
for {
// print out the number
fmt.Println(num)
// stop the iteration execution
// if the num is greater than or equals 5
if num >= 5 {
break
}
// increase the num value by 1
num++
}
}
|
Output
1
2
3
4
5
Based on the code above, the variable called num is created with initial value equals 1. The for loop is used with condition if the value of num is greater than or equals 5 then the loop execution is stopped.
This is another basic syntax to create a for loop.
for initial_state; condition; post-condition {
// code..
}
|
Based on the syntax above, there are three components:
-
initial_state is a initial condition or state in a loop.
-
condition is a certain condition that needs to be fulfilled to execute code inside for block.
-
post-condition is a code that is executed until the condition is not fulfilled.
This is the example of using for loop with three components.
package main
import "fmt"
func main() {
fmt.Println("Numbers from 1 to 5")
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
|
Output
Numbers from 1 to 5
1
2
3
4
5
Based on the code above, the for loop is specified with these components:
-
The initial state is a variable called i equals 1.
-
The condition is if the value of i less than or equals 5. If this condition is fulfilled, then the post condition code is executed then the code inside for block is executed.
-
The post condition is to increase i value by 1.
This is the list of operators that is usually used together with loop.
Operator |
Description |
+= |
var += 2 equals to var = var + 2 |
-= |
var -= 2 equals to var = var - 2 |
*= |
var *= 2 equals to var = var * 2 |
/= |
var /= 2 equals to var = var / 2 |
%= |
var %= 2 equals to var = var % 2 |
++ |
var++ equals to var = var + 1 |
-- |
var-- equals to var = var - 1 |
Go program to reverse a given string
package main
import (
"fmt"
"strings"
)
func main() {
// create a sample string
var sample string = "firstname"
// split the sample string
var letters []string = strings.Split(sample, "")
// create a reversed variable
var reversed string = ""
// append letter from the last index
for i := len(sample) - 1; i >= 0; i-- {
reversed += letters[i]
}
// print out the reversed string
fmt.Println("Original: ", sample)
fmt.Println("Reversed: ", reversed)
}
|
Output
Original: firstname
Reversed: emantsrif
Based on the code above, the sample string is created then splitted using Split() method. The for loop is used to append all the characters from the splitted string from the last index. The sample string and the reversed string is printed out.
The break and continue keyword
There are two keywords that are usually used in loop. The break is used to stop the execution whilst the continue is used to continue to the next execution. In this example, the break and continue is used.
package main
import "fmt"
func main() {
for i := 1; i <= 7; i++ {
// if the value of "i" equals 6
// stop the execution
if i == 6 {
break
}
// if the value of "i" is even number
// continue to the next execution
if i%2 == 0 {
continue
}
// print out the value of "i"
fmt.Println(i)
}
}
|
Output
1
3
5
Based on the code above, the break keyword is used to stop the execution if the value of i equals 6. The continue keyword is used to continue to the next execution if the value of i is an even number.
Iteration with for range
The for range loop is usually used together with built-in data structure in Go like slice, map and array. This is the basic syntax of for range.
for key, value := range values {
// code..
}
|
How do we iterate all items from slice in go lang
In this example, the for range loop is used to print out all the items inside slice (slice is similar with list).
package main
import "fmt"
func main() {
// create a slice of integers
var numbers []int32 = []int32{12, 45, 17, 44, 76}
// print out all items in slice
// with for range
for _, number := range numbers {
fmt.Println(number)
}
}
|
Output
12
45
17
44
76
Based on the code above, the slice of integers called numbers is created then all the items inside slice is printed out using for range loop.
Go Program to calculate average of integers
In this example, the for range is used to calculate an average from many integers.
package main
import "fmt"
func main() {
// create a slice of integers
var numbers []int = []int{12, 45, 17, 44, 76}
// create a sum variable
// to store the sum of all numbers
var sum int = 0
// calculate sum of all numbers
for _, number := range numbers {
sum += number
}
// calculate the average
var result int = sum / len(numbers)
fmt.Println("The average result: ", result)
}
|
Output
The average result: 38
Based on the code above, the average calculation is started with the sum calculation using for range then the result of sum calculation is divided by the number of the items (len(numbers)). Then the average calculation result is printed out.
In this example, the for range is used to print out all the key value pairs in map.
package main
import "fmt"
func main() {
// create a map
var student map[string]string = map[string]string{
"name": "nathan mckane",
"course": "algorithm",
"id": "RVWST001",
}
// iterate through map
// to print out the key value pairs
for key, value := range student {
fmt.Println(key, ": ", value)
}
}
|
Output
name : nathan mckane
course : algorithm
id : RVWST001
Nested loop
The nested loop is also available if needed. In this example, the nested loop is used to iterate through 2 dimensional slice.
package main
import "fmt"
func main() {
// create 2D slice
var numbers [][]int = [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i := 0; i < len(numbers); i++ {
for j := 0; j < len(numbers[i]); j++ {
fmt.Println(numbers[i][j])
}
}
}
|
Output
1
2
3
4
5
6
7
8
9
Based on the code above, the inner loop is executed then the outer loop is executed.
I hope this article is helpful to learn iteration or loop in Go Programming Language.