Loops in Go

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.

Basic For Loop

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

				
			
  • This Go code snippet demonstrates a basic for loop.
  • The loop iterates from i = 1 to i = 5.
  • Inside the loop body, fmt.Println(i) is executed to print the current value of i.
  • As a result, numbers from 1 to 5 are printed sequentially.

While Loop Equivalent in Go

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

				
			
  • This Go code snippet demonstrates how to create a loop that behaves like a while loop in other languages.
  • It initializes i to 1 outside the loop.
  • The loop condition for i <= 5 checks if i is less than or equal to 5. If true, the loop body is executed.
  • Inside the loop body, fmt.Println(i) prints the current value of i.
  • Then i is incremented by 1 using i++.
  • This process continues until the value of i becomes greater than 5, at which point the loop terminates.

Infinite Loop

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
        }
    }
}

				
			

Output

				
					1
2
3
4
5

				
			
  • We initialize a loop variable i to 1 outside the for loop.
  • Inside the for loop, we omit the loop condition, creating an infinite loop.
  • We print the value of i in each iteration and increment i by 1.
  • We use a conditional statement if i > 5 to break out of the loop when i exceeds 5.

Range Loop

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)
    }
}

				
			

Output

				
					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

				
			
  • We use the range keyword to iterate over elements of the array, slice, map, or string.
  • Inside the loop, we use two variables to capture the index (or key) and the value of each element.
  • We print the index (or key) and the value in each iteration.

Loop Control Statements

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'
    }
}

				
			

Output

				
					1
2
1
2
4
5
1
2
3
4
5

				
			
  • This Go code snippet demonstrates the usage of control flow statements: break, continue, and goto.
  • The break statement is used to terminate a loop prematurely when a certain condition is met.
  • In the first loop, the break statement terminates the loop when i equals 3.
  • The continue statement skips the current iteration of a loop when a certain condition is met.
  • In the second loop, the continue statement skips printing the value of i when it equals 3.
  • The goto statement is used to transfer control to a labeled statement.
  • In the third loop, the 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 !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India