Page Content

Tutorials

What Is Mean By Loops In Go Language With Code Examples

Loops in Go Language

A basic programming construct that enables a program to repeat a block of code several times is called a loop. For automating repeated operations like counting, processing lists of things, or acting until a condition is met, this is essential. In contrast to several other programming languages, which give multiple loop types (such as while, do, until, and foreach), Go solely offers the for loop. Through the centralisation of looping logic, this single method seeks to make Go code more legible and understandable.

The for loop in Go is flexible and has multiple applications:

for loop

An initial statement, a condition, and a post statement are the three optional parts of this most popular kind of for loop, which are divided by semicolons.

Initial Statement: Implemented once at the start of the loop. The loop is scoped for variables declared here using the short declaration operator (:=).

Condition: A boolean expression is assessed before to every iteration. The loop body runs if it is true; if it is false, the loop ends.

Post Statement: Carried out after every loop body iteration. It is frequently employed for counter incrementation and decrementation.

Example: Making even/odd numbers and counting from 1 to 10:

package main
import "fmt"
func main() {
    for i := 1; i <= 10; i++ { // i := 1 is initial, i <= 10 is condition, i++ is post
        if i % 2 == 0 { // % operator finds the remainder 
            fmt.Println(i, "even")
        } else {
            fmt.Println(i, "odd")
        }
    }
}

Output

1 odd
2 even
3 odd
4 even
5 odd
6 even
7 odd
8 even
9 odd
10 even
  • I is set to 1 in this loop.
  • It keeps on until i is less than or equal to 10.
  • Following each print, the ++ operator is used to increase i by 1.
  • The inside if-else line uses the residue of dividing by two to determine whether i is even or odd. If the remainder is zero, it is even; if not, it is odd.

for loop

When the initial and post statements are removed, Go’s for loop can also function similarly to a while loop in other languages, leaving only the condition.

Example: A straightforward countdown:

package main
import (
    "fmt"
    "time" // Used for time.Sleep 
)
func main() {
    var count = 10 // Variable declared outside the loop
    for count > 0 { // Condition only
        fmt.Println(count)
        time.Sleep(time.Second) // Pauses execution for 1 second 
        count-- // Decrements count 
    }
    fmt.Println("Liftoff!")
}

Output

10
9
8
7
6
5
4
3
2
1
Liftoff!
  • After the loop ends, the count variable is still accessible because it was declared outside of its scope.
  • As long as count exceeds 0, the loop keeps going.
  • This would create an infinite loop if count– (the decrement operator) were absent as count > 0 would always be true.

Infinite Loop with and

An endless loop is produced when a for loop is used without any assertions or conditions for {}. A break statement is required in order to conditionally escape such a loop. The innermost loop it is called within is instantly terminated by the break statement.

In order to go to the next iteration of the loop, a continue statement skips the remainder of the current one. If statements usually accompany both break and continue.

Example: An easier version of a guessing game:

package main
import (
    "fmt"
    "math/rand"
    "time"
)
func main() {
    rand.Seed(time.Now().UnixNano()) // Seeds the random number generator 
    target := rand.Intn(100) // Generates a random number between 0 and 99 
    for { // Infinite loop [20, 22, 29]
        var guess int
        fmt.Print("Enter a guess: ")
        _, err := fmt.Scanf("%d", &guess) // Reads user input 
        if err != nil {
            fmt.Println("Invalid guess: err:", err)
            continue // Skips to the next loop iteration if input is invalid 
        }
        if guess > target {
            fmt.Println("Too high!")
        } else if guess < target {
            fmt.Println("Too low!")
        } else {
            fmt.Println("You win!")
            break // Exits the loop if the guess is correct 
        }
    }
    fmt.Println("Game Over!") // This line runs after the break
}

Output

Enter a guess: 200
Too high!
Enter a guess: 7
Too low!
Enter a guess: 719
Too high!
Enter a guess: 

The moment.As a “bad” practice, sleep calls are typically avoided in real programs for waiting, but they are common in examples. Time.Generally speaking, after or channels are favoured for synchronisation.

for-range

Iterating over elements of sequential or collection data types, such as arrays, slices, strings, and maps, is made simple and straightforward with the help of the for-range keyword.

Iterating over Arrays and Slices: Both the current element’s value and index are returned by the for-range function. You can use the blank identifier (_) to remove the unnecessary variable and prevent compiler problems for “declared and not used” variables if you only need the value (or the index).

Iterating over Strings: Iterating over a string’s runes (Unicode code points) is what happens when you use for-range. It gives back both the character itself and its byte index.

The byte index i might not be sequential for multi-byte characters (like ‘¿’, ‘ó’ in UTF-8).

Iterating over Maps: Every time a map is iterated, for-range returns the key and its corresponding value. The sequence of key-value pairs returned can vary from run to run; it is crucial to remember that iteration over maps is not ordered.

Nested Loops

Loops can be nestled inside of one another. When working with multi-dimensional data structures, such as arrays of arrays or slices of slices, or when an action must be repeated for each element in a bigger iteration, this is helpful.

Example: I

package main
import "fmt"
func main() {
    ints := [][]int{
        []int{0, 1, 2},
        []int{-1, -2, -3},
        []int{9, 8, 7},
    }
    // Outer loop iterates through the outer slice (each inner slice) 
    for _, innerSlice := range ints {
        // Inner loop iterates through the elements of each inner slice
        for _, value := range innerSlice {
            fmt.Println(value)
        }
    }
}

Output

0
1
2
-1
-2
-3
9
8
7
  • Iterating across a slice with several dimensions:
  • From ints, the outer loop extracts each []int (slice of numbers).
  • After that, the inner loop goes through each value in that innerSlice.
  • Only the innermost loop that the break statement is in is stopped from continuing. A labelled break is a typical programming practice if you wish to exit several nested loops.

You can also read What Are Go Decision Making Statements With Code Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index