Go provides a single looping construct, the for loop, which can be used in multiple ways to implement iteration. It can behave like a traditional for loop, a while loop, an infinite loop, and can also iterate over collections such as arrays, slices, strings, maps, and channels using the range keyword.
Example: Print a Message Multiple Times Using a Loop
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("Learning Go Loops")
}
}
Output
Learning Go Loops Learning Go Loops Learning Go Loops
Types of Loops in Go
| Loop Type | Description |
|---|---|
| Simple for loop | Executes code for a fixed number of iterations. |
| for as a while loop | Executes while a condition remains true. |
| Infinite for loop | Runs indefinitely until terminated. |
| for-range loop | Iterates over collections such as arrays, slices, strings, maps, and channels. |
Simple For Loop
A simple for loop is used when a block of code needs to be executed a fixed number of times. It consists of three optional components: initialization, condition, and post statement.
Example: Print Numbers from 1 to 5
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}
Output
1 2 3 4 5
Explanation:
- Initialize i with 1.
- Continue executing the loop while i <= 5.
- Increment i by 1 after each iteration.
- Print the value of i during every iteration.
Syntax:
for initialization; condition; post {
// Statements
}
- Initialization: Executes once before the loop starts and is typically used to declare or initialize variables.
- Condition: Evaluated before each iteration. The loop continues as long as the condition is true.
- Post statement: Executes after each iteration and is commonly used to increment or update variables.
Time Complexity: O(n)
Auxiliary Space: O(1)
Note: All three components (initialization, condition, and post statement) are optional in Go, but semicolons (;) are required when using this loop form.
Infinite For Loop
An infinite for loop runs continuously because it does not contain an initialization statement, condition, or post statement. It is commonly used in applications that need to run indefinitely, such as servers, background tasks, and event listeners.
Example: Print Numbers Continuously
package main
import "fmt"
func main() {
count := 1
for {
fmt.Println("Count:", count)
count++
if count > 5 {
break
}
}
}
Output
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
Explanation:
- Create an infinite for loop without any loop expressions.
- Print the value of count in each iteration.
- Increment count after every iteration.
- Use the break statement to terminate the loop when count becomes greater than 5.
Note: Infinite loops should usually be used with a termination condition such as break; otherwise, the program will continue running indefinitely.
Syntax:
for {
// Statements
}
Time Complexity: O(n)
Auxiliary Space: O(1)
For Loop as a While Loop
Go does not have a separate while loop. Instead, a for loop with only a condition can be used to achieve the same behavior. The loop continues executing as long as the condition evaluates to true.
Example:
package main
import "fmt"
func main() {
sum := 0
num := 1
for num <= 5 {
sum += num
num++
}
fmt.Println("Sum:", sum)
}
Output
Sum: 15
Explanation:
- Initialize sum with 0 and num with 1.
- Use a for loop with only a condition (num <= 5).
- Add the current value of num to sum during each iteration.
- Increment num by 1.
- Print the final sum after the loop ends.
Syntax:
for condition {
// Statements
}
Time Complexity: O(n)
Auxiliary Space: O(1)
For-Range Loop
The range keyword is used with a for loop to iterate over collections such as arrays, slices, strings, maps, and channels. During each iteration, range returns the index and the corresponding value.
Example: Iterate Over a Slice
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
Output
Index: 0, Value: 10 Index: 1, Value: 20 Index: 2, Value: 30 Index: 3, Value: 40
Explanation:
- Create a slice named numbers.
- Use for-range to iterate over the slice.
- index stores the position of each element.
- value stores the element at the corresponding position.
- Print both the index and value during each iteration.
Syntax:
for index, value := range collection {
// Statements
}
- index: Stores the position of the current element.
- value: Stores the current element being iterated.
- collection: Represents an array, slice, string, map, or channel.
Time Complexity: O(n)
Auxiliary Space: O(1)
Iterate Over Strings Using For-Range
The for-range loop can iterate over the characters of a string. During each iteration, range returns the starting byte index and the corresponding Unicode code point (rune).
Example: Iterate Over Characters in a String
package main
import "fmt"
func main() {
str := "Hello"
for index, char := range str {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
}
Output
Index: 0, Character: H Index: 1, Character: e Index: 2, Character: l Index: 3, Character: l Index: 4, Character: o
Explanation:
- Create a string named str.
- Use for-range to iterate over the string.
- index stores the starting byte index of each character.
- char stores the corresponding Unicode character (rune).
Syntax:
for index, char := range str {
// Statements
}
- index: Stores the starting byte index of the current character.
- char: Stores the Unicode code point (rune).
- str: Represents the string being iterated.
Time Complexity: O(n)
Auxiliary Space: O(1)
Note: The range keyword iterates over Unicode code points (runes) rather than individual bytes, making it suitable for working with UTF-8 encoded strings.
Example: Iterate Over a Unicode String
package main
import "fmt"
func main() {
str := "Go"
for index, char := range str {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
}
Output
Index: 0, Character: G Index: 1, Character: o
Iterate Over Maps Using For-Range
The for-range loop can iterate over the key-value pairs of a map. During each iteration, range returns a key and its corresponding value.
Example: Iterate Over a Map
package main
import "fmt"
func main() {
students := map[int]string{
101: "Alice",
102: "Bob",
103: "Charlie",
}
for key, value := range students {
fmt.Printf("ID: %d, Name: %s\n", key, value)
}
}
Output
ID: 101, Name: Alice ID: 102, Name: Bob ID: 103, Name: Charlie
Note: The output order may vary because Go does not guarantee the iteration order of map elements.
Explanation:
- Create a map named students.
- Use for-range to iterate over the map.
- key stores the current map key.
- value stores the corresponding value.
Syntax:
for key, value := range myMap {
// Statements
}
- key: Stores the key of the current map entry.
- value: Stores the value associated with the key.
- myMap: Represents the map being iterated.
Time Complexity: O(n)
Auxiliary Space: O(1)
Iterate Over Channels Using For-Range
The for-range loop can iterate over values received from a channel. The loop continues until the channel is closed.
Example: Iterate Over Values from a Channel
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
ch <- 10
ch <- 20
ch <- 30
close(ch)
}()
for value := range ch {
fmt.Println(value)
}
}
Output
10 20 30
Explanation:
- Create an integer channel named ch.
- Use a goroutine to send values to the channel.
- Close the channel after sending all values.
- Use for-range to receive and print each value.
- The loop automatically terminates when the channel is closed.
Syntax:
for value := range ch {
// Statements
}
- value: Stores the current value received from the channel.
- ch: Represents the channel being iterated.
Time Complexity: O(n)
Auxiliary Space: O(1)
Important Points
- Go provides only one loop construct: for.
- Parentheses () are not used around loop expressions.
- Curly braces {} are mandatory and the opening brace must be on the same line as the for statement.
- The range keyword can iterate over arrays, slices, strings, maps, and channels.
- Empty or nil collections result in zero iterations.