18. For

Running Loops

For Statement

When we need to repeat things, that's where loops come into play. Unlike other programming languages, Go has only single construct for looping, for

Traditional loop

We can write traditional for loop using loop variable similar to most other programming languages.

for initialization; condition; post statement {

code to execute

}

main.go
for i := 1; i < 10; i++ {
    fmt.Printf("Hello %d \n", i)
}

For loop as while loop

We can only define the condition part in for loop and it will act like a while loop. We need to make sure initialization if any required as well as post conditioned are handled.

for condition { code to execute }

main.go
j := 1
for j < 10 {
	fmt.Printf("Hello %d\n ", j)
	j = j + 1
}

If we skip the line 4 above, we end up creating infinite loop.

Continue and Break

We can use continue and break statement inside of for loop to control flow. continue is used to run next iteration of loop and abandon remaining code in current loop iteration. break is used to break out of the loop.

main.go
for k := 1; k < 20; k++ {
	if k%2 == 0 {
		continue
	}
	fmt.Printf("Hello  %d\n", k)
}
for k := 1; k < 20; k++ {
	if k == 13 {
		break
	}
	fmt.Printf("Hello  %d\n", k)
}

The first for loop above will not print if value is even and continue to next iteration. Second for loop will break the loop when k reaches 13.

Infinite Loop

We can also skip condition part of for loop which will create infinite loop. Make sure there is way to break out of for loop when no condition is provided.

main.go
for {
    fmt.Println("Hello!")
    // break based on some condition to exit infinite loop
}

Iterating over range

Go can easily iterate over arrays,maps and slices using range keyword.

When iterating over slice, range returns index and value from slice.

main.go
data := []string{"a", "b", "c"}
for index, value := range data {
	fmt.Println(index, value)
}

When iterating over maps, range returns key and value.

main.go
capitals := map[string]string{
	"India":   "Pune",
	"England": "London",
	"U.S.":    "Washington",
}
for key, value := range capitals {
	fmt.Println(key, value)
}

range is also useful for getting each rune from string.

main.go
greetings := "नमस्कार"
for _, char := range greetings {
	fmt.Printf("%c\n", char)
}

Last updated