Loops are essential constructs in programming that allow us to execute a block of code repeatedly until a certain condition is met. In Go, there are various types of loops available, each serving different purposes. This chapter aims to provide a comprehensive guide to loops in Go, covering basic for loops, while loops, and advanced concepts like range loops and loop control statements.
The most commonly used loop in Go is the for loop. It allows us to execute a block of code repeatedly for a specified number of times. Let’s explore a basic example:
package main
import "fmt"
func main() {
// Basic for loop to print numbers from 1 to 5
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
Output
1
2
3
4
5
i = 1
to i = 5
.fmt.Println(i)
is executed to print the current value of i
.Although Go does not have a built-in while loop, we can achieve the same functionality using a for loop with a conditional expression. Let’s see an example:
package main
import "fmt"
func main() {
// Equivalent of while loop in Go
i := 1
for i <= 5 {
fmt.Println(i)
i++
}
}
Output
1
2
3
4
5
while
loop in other languages.i
to 1
outside the loop.for i <= 5
checks if i
is less than or equal to 5
. If true, the loop body is executed.fmt.Println(i)
prints the current value of i
.i
is incremented by 1
using i++
.i
becomes greater than 5
, at which point the loop terminates.An infinite loop is a loop that continues indefinitely until it is explicitly terminated. In Go, we can create an infinite loop using the for loop without a loop condition. Let’s see an example:
package main
import "fmt"
func main() {
// Infinite loop
i := 1
for {
fmt.Println(i)
i++
if i > 5 {
break // Terminates the loop when i exceeds 5
}
}
}
1
2
3
4
5
i
to 1 outside the for loop.i
in each iteration and increment i
by 1.if i > 5
to break out of the loop when i
exceeds 5.In Go, the range loop is used to iterate over elements of various data structures like arrays, slices, maps, or strings. Let’s see some examples:
package main
import "fmt"
func main() {
// Range loop over an array
arr := [3]int{1, 2, 3}
for index, value := range arr {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
// Range loop over a slice
slice := []string{"apple", "banana", "cherry"}
for index, value := range slice {
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
// Range loop over a map
m := map[string]int{"a": 1, "b": 2, "c": 3}
for key, value := range m {
fmt.Printf("Key: %s, Value: %d\n", key, value)
}
// Range loop over a string
str := "Hello"
for index, char := range str {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
}
Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry
Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
Index: 0, Character: H
Index: 1, Character: e
Index: 2, Character: l
Index: 3, Character: l
Index: 4, Character: o
range
keyword to iterate over elements of the array, slice, map, or string.Go provides loop control statements like break
, continue
, and goto
to control the flow of loops. Let’s see how they work:
package main
import "fmt"
func main() {
// Example of break statement
for i := 1; i <= 5; i++ {
if i == 3 {
break // Terminates the loop when i equals 3
}
fmt.Println(i)
}
// Example of continue statement
for i := 1; i <= 5; i++ {
if i == 3 {
continue // Skips the current iteration when i equals 3
}
fmt.Println(i)
}
// Example of goto statement
i := 1
loop:
if i <= 5 {
fmt.Println(i)
i++
goto loop // Jumps to the label 'loop'
}
}
1
2
1
2
4
5
1
2
3
4
5
break
, continue
, and goto
.break
statement is used to terminate a loop prematurely when a certain condition is met.break
statement terminates the loop when i
equals 3
.continue
statement skips the current iteration of a loop when a certain condition is met.continue
statement skips printing the value of i
when it equals 3
.goto
statement is used to transfer control to a labeled statement.goto
statement jumps to the label loop
, effectively creating an infinite loop until the condition i <= 5
is no longer true.Loops are essential constructs in Go for executing code repeatedly. By understanding the various types of loops, including for loops, while loops, range loops, and loop control statements, you'll be able to write more efficient and concise code. Additionally, mastering the usage of loops will enhance your ability to manipulate data structures and control program flow effectively in Go. Happy coding !❤️