Go Fundamentals: The Power of Loops

Topic Overview and Actualization

Hello, Explorer! Today, we dive into the world of Go loops. In programming, loops are essential tools for automating repetitive tasks efficiently — much like binge-watching that thrilling TV series. In this lesson, we'll explore the versatile loop constructs in Go and practice applying them to Go's slices and strings, taking advantage of their simplicity and power.

Understanding Looping

Imagine listening to your favorite album on repeat. That's the core concept of loops in programming. In Go, a for loop can help us achieve this repetitive capability. Let's use a simple for loop to greet each of our friends.

package main

import "fmt"


func main() {
    friends := []string{"Alice", "Bob", "Charlie", "Daniel"}
    for _, friendName := range friends {
        // For each friendName, prints the greeting
        fmt.Println("Hello,", friendName + "! Nice to meet you.")
    }
    // Output:
    // Hello, Alice! Nice to meet you.
    // Hello, Bob! Nice to meet you.
    // Hello, Charlie! Nice to meet you.
    // Hello, Daniel! Nice to meet you.
}

Loops enable us to execute repetitive sequences automatically and efficiently, as shown in this simple example.

For Loop in Go

The for loop is the only loop construct in Go, and it provides great flexibility. Here's how it normally operates:

  1. Initialization: Set up the loop variable. This step runs once when the loop starts.
  2. Condition: A boolean expression that controls the loop's execution. If true, the loop continues; if false, it stops.
  3. Post: Updates the loop variable. This step executes after the loop body's iteration but before evaluating the next condition.
  4. Loop Body: The block of code executed each time the condition is true.

The structure of a for loop is for initialization; condition; post { loop body }.

Let's print a range of numbers using a for loop in Go:

Go
package main

import "fmt"

func main() {
    for num := 0; num < 5; num++ {
        // This line prints numbers from 0 to 4
        fmt.Println(num)
    }
}

In each cycle of the loop, the variable (num) is updated before the loop body executes, creating a straightforward repetitive sequence.

Range Keyword in For Loop

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal