Fundamentals of Go Loops
Go programming language provides several loop constructs to execute a block of code repeatedly. The most commonly used loop in Go is the for
loop, which can be used to iterate over arrays, slices, maps, and other data structures. Go also supports the while
loop and the do-while
loop, although they are less frequently used.
Basic for Loop
The basic for
loop in Go has the following syntax:
for initialization; condition; post {
// code block
}
Here's an example that prints the numbers from 1 to 5:
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
The loop initializes the variable i
to 1, checks the condition i <= 5
, and then executes the code block. After each iteration, the post statement i++
increments the value of i
.
Infinite Loops
Go also supports infinite loops, which can be used to create programs that run continuously. The simplest way to create an infinite loop is to use the for
keyword without any condition:
for {
// code block
}
This loop will run indefinitely until it is explicitly terminated, such as by using the break
statement or by pressing Ctrl+C
in the terminal.
Looping over Arrays and Slices
Go's for
loop can be used to iterate over the elements of an array or slice. The following example demonstrates how to loop over an array of integers:
numbers := []int{1, 2, 3, 4, 5}
for i, num := range numbers {
fmt.Printf("Index: %d, Value: %d\n", i, num)
}
The range
keyword is used to iterate over the elements of the array or slice. The loop variable i
represents the index of the current element, and the loop variable num
represents the value of the current element.
By using the for
loop and its various constructs, you can easily implement a wide range of loop-based algorithms and control structures in your Go programs.