Understanding For Loops in Golang: The Ultimate Beginners Guide in 2022 with Code Examples
The only way to iterate in Golang is to use the for
loop construct. There’s no for-each or a while
statement–but we can emulate them with the for
loop statement.
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
In this guide will talk about the following topics:
- What goes into a
for
loop? - How to emulate a for-each statement in Golang
- How to emulate a
while
statement in Golang - How to emulate an infinite loop without any statements
- How to exit a
for
loop
Let’s dive in!
What goes into a for
loop?
The basic for
loop has three simple components, all separated by semicolons (;
).
for i := 0; i < 10; i++ {
// ...some execution here
}
The first component is the initial statement. This is the area where you typically create a variable with number value.
i := 0;
The second component is the condition expression. At this point of the loop, Golang is going to try to evaluate a statement to determine whether it goes to the final component.
i < 10;
The final component is the called the post statement. After the evaluation passes, and the code with the curly braces ({}
) gets executed, the post statement will execute after the iteration.
i++
Here’s the kicker to the components on a for
loop in Golang, they’re all optional.
How to emulate a foreach statement in Golang
A foreach
loop does not exist in Golang–but you can emulate it with a range
statement in the for
components!
Here are 3 basic foreach
patterns you can use with a range
loop.
Example 1. Arrays
Let’s say you have a an array of strings:
cats := []string{"Monkey", "Mr. Whiskers"}
In a foreach
statement you should have access to the index of the array & the value.
cats := []string{"Monkey", "Mr. Whiskers"}
fmt.Println(cats)
for i, name := range cats {
fmt.Println(i, name)
}
The output would look something like this:
0 Monkey
1 Mr. Whiskers
Example 2. Strings
You can also iterate over strings–you’d be iterating over each character within the string value.
for i, ch := range "Mr. Whiskers" {
fmt.Printf("%#U starts in position %d\n", ch, i)
}
The output would look something like this:
U+004D 'M' starts in position 0
U+0072 'r' starts in position 1
U+002E '.' starts in position 2
U+0020 ' ' starts in position 3
U+0057 'W' starts in position 4
U+0068 'h' starts in position 5
U+0069 'i' starts in position 6
U+0073 's' starts in position 7
U+006B 'k' starts in position 8
U+0065 'e' starts in position 9
U+0072 'r' starts in position 10
U+0073 's' starts in position 11
Example 3. Maps
cats := map[int]string{
1: "Mr. Whiskers",
2: "Monkey",
3: "Smokey",
}
for k, v := range cats {
fmt.Println(k, v)
}
Skip index or value
You can skip the index or value of a range
loop by using an underscore (_
).
for i, _ := range cats
for _, value := range cats
How to emulate a while
statement in Golang
To make a while
loop in Golang, you’ll need to skip the first and third component of a for
loop structure.
a := 1
for a < 10 {
a *= 2
}
You can see in the for
loop structure, it’s just the evaluation and init or post statements, and no semicolons (;
)
How to emulate an infinite loop without any statements
All components in a for
loop are optional. So you have have zero statements or conditions!
sum := 0
for {
sum++ // repeated forever
}
I haven’t come across a scenario where this is useful, but it’s there just incase.
How to exit a for
loop
To break a loop you need to use the special keyword break
inside the curly braces ({}
) of a for
loop.
sum := 0
for {
if sum > 4 {
break;
}
sum++
}
fmt.Println(sum)
Do not confuse break
with the another special keyword called continue
.
The keyword continue
in a for
loop only skips to the next iteration of the loop. It does not completely break the loop in Golang.
I like to tweet about Golang and post helpful code snippets. Follow me there if you would like some too!