Golang for loop

Golang for loop

In go programming language we have only one looping statement for. We use keywords like break, continue and range with for loop based on the use-case that we have.

Structure of for loop in golang

for <initialization>; <condition>; <step> {
    sum += i
}

We can have a initialization in for loop to initialize the data and condition to check whether to continue with next iteration. After the iteration we have a step to update it's contents to be checked inside condition. It's not necessary to have all three of these to work with for loop.

Let's write a simple go program to print the first ten numbers.

package main
import "fmt"

func main(){
   for i := 1; i <= 10 ; i++ {
       fmt.Println(i)
   } 
}

break keyword in golang

The break keyword allows you to terminate a loop at that point and continue execution at the statement following the end of the for loop block.

Example: golang-break.go

package main
import "fmt"

func main() {
    i := 0
    for { //since there are no checks, this is an infinite loop
        if i >= 3 {
      break
    }
        fmt.Println("i = ", i)
        i++;
    }
    fmt.Println("A statement just after for loop.") 
}

Output:

i =  0
i =  1
i =  2
A statement just after for loop.

continue keyword in golang

The continue statement allows us to skip the particular loop iteration when it is used.

Example: Print all odd numbers from 1 to 10.

package main

import "fmt"

func main() {
   for i := 0; i<= 10 ; i++ {
        if i%2 == 0 { 
            continue
        }
        fmt.Println(i)
    }
}

Output:

1
3
5
7
9

if you see the above output it skipped the even numbers to print. That's because we used continue statement.

range keyword in golang

The range keyword allows us to iterate over items of a list or a map. Let's implement it.

package main

import "fmt"

func main() {

    // using range with an array
    a := [...]string{"a", "b", "c", "d"}
    for index, value := range a {
        fmt.Println("Array index = ", index, ", Index value = ", value)
    }

    // using range with a map
    // iterate only keys
    capitals := map[string] string {"France":"Paris", "Italy":"Rome", "Japan":"Tokyo" }
    for key := range capitals {
        fmt.Println("Map Key = ", key)
    }

    //iterate keys and values
    for key, val := range capitals {
        fmt.Println("Map Key = ", key, ", Value = ", val)
    }
}

Output:

Array index =  0 , Index value =  a
Array index =  1 , Index value =  b
Array index =  2 , Index value =  c
Array index =  3 , Index value =  d
Map Key =  France
Map Key =  Italy
Map Key =  Japan
Map Key =  Japan , Value =  Tokyo
Map Key =  France , Value =  Paris
Map Key =  Italy , Value =  Rome