Post

Go loop

Comprehensive guide to for loops in Go, covering basic loops, multiple variables, infinite loops, break, continue, labels, and range-based iteration over slices, maps, and strings.

This program covers every variation of the for loop in Go, which is the only loop construct in the language. It demonstrates basic incrementing loops, iterating with two variables, omitting the initializer, while-style loops, infinite loops with break, the continue keyword for skipping iterations, labeled loops for breaking out of nested loops, and range-based iteration over slices, maps, and strings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main

import (
	"fmt"
	// "strconv"
	// "math"
	// "reflect"
	// "math"
)

func basicLoop()  {
	for i := 0; i < 5; i++ {
		fmt.Printf("Number: %v\n", i)
	}
}


func everyOther()  {
	for i := 0; i < 5; i = i + 2 {
		fmt.Printf("Number: %v\n", i)
	}
}

func loopOverTwoVariables()  {
	for i, j := 0, 0; i < 5; i, j = i + 1, j + 3 {
		fmt.Printf("i: %v, j: %v\n", i, j)
	}
}

func play()  {
	for i:= 0; i < 5; i++ {
		fmt.Printf("Number: %v\n", i)
		if i%2 == 0 {
			i /= 2
		} else {
			i = 2*i + 1
		}
	}
}


func initializerAtSomeOtherPlace()  {
	i := 0
	for ; i < 5; i++ {
		fmt.Printf("Number: %v\n", i)
	}
}

func pythonLike()  {
	i := 0
	// for i < 5 {   <- works just fine withour semicolons
	for ; i < 5 ; {
		fmt.Printf("Number: %v\n", i)
		i++
	}
}

func infiniteForLoop()  {
	i := 0
	for {
		fmt.Printf("Number: %v\n", i)
		i++
	}
}


func infiniteForLoopWithBreak()  {
	i := 0
	for {
		fmt.Printf("Number: %v\n", i)
		i++
		if i == 5 {
			fmt.Printf("Breaking from Infinite Loop! number: %v\n", i)
			break
		}
	}
}


func forLoopWithContinueKeyWork()  {
	for i := 0; i < 10; i ++ {
		if i%2 == 0 {
			// the keyword "continue" is a special keyword
			// and if this condition above is true that we
			// stop here and don't go and print anything !!!
			// we sort of continuing back to main loop
			continue
		}
		fmt.Printf("Number: %v\n", i)
	}
}

func nestedForLoop()  {
	for i := 1; i <= 3; i++ {
		for j := 1; j <=4; j++ {
			fmt.Printf("Multiply %v(i) * %v(j) = %v\n", i, j, i*j)
		}
	}
}


func breakOutOfNestedForLoop()  {
// This "label" below "tells to" the "break" keyword
// which loop to exit!!! Please notice that if this label not used
// only inner most loop would be exited
Labelloop:
	for i := 1; i <= 3; i++ {
		for j := 1; j <=4; j++ {
			fmt.Printf("Multiply %v(i) * %v(j) = %v\n", i, j, i*j)
			if i * j >= 3 {
				fmt.Printf("Breaking out of nested for loop because of condition based on label!!!\n")
				break Labelloop
			}
		}
	}
}


func collectionForLoop()  {
	s := []int{1, 2, 3}
	fmt.Printf("Element: %v\n", s)
	fmt.Println("")
	for k, v := range s {
		fmt.Printf("Element: %v(k): %v(v)\n", k, v)
	}
	fmt.Println("")
	// maps
	statePopulation := make(map[string]int)
    statePopulation = map[string]int{
        "California": 2341232,
        "Texas": 3341232,
        "Florida": 4341232,
        "New York": 5341232,
        "Illinois": 6341232,
        "Ohio": 7341232,
	}

	fmt.Println("")
	for k,v := range statePopulation {
		fmt.Printf("Element: %v(k): %v(v)\n", k, v)
	}

	fmt.Println()
	//  if we only care for "keys"
	for k := range statePopulation {
		fmt.Printf("Element: %v(k)\n", k)
	}

	fmt.Println("")
	//  if we only care for "values"
	for _, v := range statePopulation {
		fmt.Printf("Element: %v(v)\n", v)
	}
	fmt.Println("")
	// strings
	st := "hello Go!"
	for k, v := range st {
		fmt.Printf("Element: %v(k): %v(v), %v(v) \n", k, v, string(v))
	}


}

func main() {
	// basicLoop()
	// everyOther()
	// loopOverTwoVariables()
	// play()
	// initializerAtSomeOtherPlace()
	// pythonLike()
	// infiniteForLoop()
	// infiniteForLoopWithBreak()
	// forLoopWithContinueKeyWork()
	// nestedForLoop()
	// breakOutOfNestedForLoop()
	collectionForLoop()
}
This post is licensed under CC BY 4.0 by the author.