A loop is a block of code that runs until a specified condition is met or a required number of repetitions is completed. Loops are convenient for solving tasks where a program needs to repeat the same actions multiple times.
For example, imagine you have a list of directors. You need to extract each director's last name and display it on the screen. Instead of manually accessing each element of the list, it's easier to use a loop. A loop will iterate through the list and display each last name on the screen.
In Go, there are only for
loops. There are no while
or do while
loops like in some other languages. Similar concepts are implemented using the same for loop. This design choice makes the code more readable. Developers don't have to decide on a looping strategy — if you need to repeat actions, there's for
, which can be used in various ways.
Let's explore how to create loops in Golang to solve specific tasks.
The structure of a ForClause
is simple. It consists of a condition and a body. The code inside the body executes if the condition is evaluated as true.
for i := 0; i < 6; i++ {
fmt.Println(i)
}
Here:
i := 0
is the initializer. It sets the starting value of the loop.
i < 6
is the condition. If it is evaluated as true, the code inside the loop is executed.
fmt.Println(i)
sequentially prints numbers from 0 to 5.
i++
is the post-operation that increments i
by 1 after each iteration.
The code starts with i = 0
. Since 0 < 6
, the condition is true
, and 0
is printed. Then, i++
increments i
by 1, making i = 1
. The loop continues as long as i < 6
.
When i
becomes 6, the condition i < 6
is false
, and the loop stops. The number 6 is not printed.
Output:
0
1
2
3
4
5
You don't have to start at zero or stop at a fixed value. The for loop in Go allows you to adjust the logic as needed.
for i := 100; i < 150; i = i + 10 {
fmt.Println(i)
}
Output:
100
110
120
130
140
If you modify the condition slightly, you can include the number 150:
for i := 100; i <= 150; i = i + 10 {
fmt.Println(i)
}
Output:
100
110
120
130
140
150
You can also iterate in reverse, from the end to the beginning, by modifying the condition and the post-operation.
for i := 50; i > 0; i -= 10 {
fmt.Println(i)
}
Here, the loop starts with i = 50
. On each iteration, it checks if i > 0
. If the condition is true, it subtracts 10 from the current value of i
.
Output:
50
40
30
20
10
Note that 0 is not printed because the condition requires i > 0
.
If you remove the initializer and post-operator from the syntax, you get a simple construct that works based on a condition. The loop declaration in this case looks like this:
i := 0
for i < 6 {
fmt.Println(i)
i++
}
If you are familiar with other programming languages, you might recognize this as similar to a while
loop.
In this example, i
is defined outside the loop. The for
loop only has a condition, which keeps the loop running while i
is less than 6. Note that the increment operation (i++
), previously specified as a post-operator, is now inside the body.
Sometimes, the number of iterations is unknown in advance. You can't specify a condition for ending the loop in such cases. To avoid infinite loops, Go supports the break
keyword. Here's a simple example:
func main() {
i := 0
for {
fmt.Println("Hello")
if i == 5 {
break
}
i++
}
}
Initially, i = 0
. The loop runs indefinitely, printing "Hello" each time. However, when i
reaches 5, the break
statement is executed, and the program stops.
Go also provides another type of loop — the RangeClause
. It is similar to ForClause
, but it returns two values by default: the index of an element and its value.
package main
import "fmt"
func main() {
words := []string{"host", "man", "hostman", "cloud"}
for i, word := range words {
fmt.Println(i, word)
}
}
Output:
0 host
1 man
2 hostman
3 cloud
To omit the index, use an underscore _
as a placeholder:
package main
import "fmt"
func main() {
words := []string{"host", "man", "hostman", "cloud"}
for _, word := range words {
fmt.Println(word)
}
}
Output:
host
man
hostman
cloud
You can also use range
to add elements to a list:
package main
import "fmt"
func main() {
words := []string{"host", "man", "hostman", "cloud"}
for range words {
words = append(words, "great")
}
fmt.Printf("%q\n", words)
}
Output:
["host" "man" "hostman" "cloud" "great" "great" "great" "great"]
In this example, the word "great" is added for each element in the original length of the words
slice.
Suppose you have a slice of 10 zeros and need to populate it with numbers from 0 to 9:
package main
import "fmt"
func main() {
integers := make([]int, 10)
fmt.Println(integers)
for i := range integers {
integers[i] = i
}
fmt.Println(integers)
}
[0 0 0 0 0 0 0 0 0 0]
[0 1 2 3 4 5 6 7 8 9]
You can use range
to iterate over each character in a string:
package main
import "fmt"
func main() {
hostman := "Hostman"
for _, letter := range hostman {
fmt.Printf("%c\n", letter)
}
}
Output:
H
o
s
t
m
a
n
This allows you to process each character in a string individually.
A for
loop can be created inside another construct, making it nested. We can represent its syntax as:
for {
[Action]
for {
[Action]
}
}
First, the outer loop starts running. It executes and then triggers the inner loop. After the inner loop finishes, the program returns to the outer loop. This process repeats as long as the given condition holds or until the program encounters a break
statement.
There is also a risk of creating an infinite loop, which even the powerful resources of Hostman wouldn’t handle, as the program would never terminate. To avoid this, always ensure the condition is properly checked or use the break
operator.
Here’s a simple example to demonstrate nested loops:
package main
import "fmt"
func main() {
numList := []int{1, 2}
alphaList := []string{"a", "b", "c"}
for _, i := range numList {
fmt.Println(i)
for _, letter := range alphaList {
fmt.Println(letter)
}
}
}
Output:
1
a
b
c
2
a
b
c
This example clearly demonstrates the order of operations:
The first value from numList (1)
is printed.
The inner loop executes, printing each value from alphaList
(a
, b
, c
).
The program returns to the outer loop and prints the next value from numList
(2
).
The inner loop runs again, printing the values of alphaList
(a
, b
, c
) a second time.
Using for
loops in Go is straightforward. Depending on the task, you can choose one of the three main forms of for
or combine them to create nested constructs. You can control the loop's behavior by modifying the condition, initializer, and post-operator or by using break
and continue
statements.
Nested loops provide flexibility and power but should be used carefully to avoid infinite loops or excessive computational overhead.
You can deploy Go applications (such as Beego and Gin) on our app platform.