
Loops in GoLang
Loops in GoLang
Go supports only one type of loop: the for
loop. However, this for
loop is highly flexible and can be used in various ways to simulate other looping constructs like while
and do-while
from other languages.
Types of For Loops in Go
Basic For Loop: This is similar to the
for
loop in other languages, with an initialization statement, a condition, and a post statement.For-Range Loop: A special form of
for
used to iterate over elements in arrays, slices, maps, strings, etc.While-like For Loop: In Go, you can create a
while
loop-like behavior by omitting the initialization and post statements.Infinite For Loop: A
for
loop can be used without any conditions to create an infinite loop.
1. Basic For Loop
This loop has three components:
- Initialization: Executes once, before the loop starts.
- Condition: Checks before each iteration; if
true
, the loop continues. - Post: Executes after each iteration.
Syntax:
import "fmt"func main() { Iteration: 1Iteration: 2Iteration: 3Iteration: 4
- The loop starts with
i = 0
, and continues untili < 5
. - After each iteration,
i++
increments the value ofi
.
2. For-Range Loop
This is a simplified loop used to iterate over elements in arrays, slices, strings, maps, etc. It returns two values: the index and the value of the element.
Syntax:
// Code to execute on each iteration}
If you only care about the value and not the index, you can omit the index
by writing _
(underscore).
Example:
import "fmt"func main() { colors := []Index: 1 Color: GreenIndex: 2 Color: Blue
- The
range
keyword returns both the index and the value for each element in the slice.
3. While-like For Loop
In Go, you can create a while
-like loop by omitting the initialization and post statements. The loop will keep running as long as the condition is true.
Syntax:
// Code to execute while the condition is true}
Example:
import "fmt"func main() { i := for {
// Code to execute indefinitely}
Example:
import "fmt"func main() { count := package main
import "fmt"func main() { for i := 0; i < 10; i++ { if i == 5 { continue // Skip the iteration when i is 5 } if i == 8 { break // Exit the loop when i is 8 } fmt.Println(i) }}
Output:
123467
- When
i == 5
, thecontinue
statement skips the iteration. - When
i == 8
, thebreak
statement exits the loop.
Summary
- Basic for loop: A standard loop with initialization, condition, and post statements.
- For-range loop: Iterates over elements in arrays, slices, strings, and maps.
- While-like loop: A loop without initialization or post statements, similar to a
while
loop in other languages. - Infinite loop: A loop that runs indefinitely until explicitly broken using
break
. - Control statements:
break
andcontinue
to control loop flow.
Go's loop constructs are flexible and efficient, providing a powerful way to handle various looping scenarios.