Lesson Overview

Welcome to our lesson on Go's for loop. Loops are used to execute a block of code repeatedly. A for loop is associated with repetitive tasks that you want to accomplish - for example, reading each page of a book, one after another. By the end of this journey, you will understand and be able to use the basic for loop and the range clause in Go.

Understanding the Basic For Loop in Go

Imagine you are counting your favorite collection of stickers. You take one, count it, and continue the process until all stickers are counted. This is exactly how the basic for loop works in Go!

Here's the syntax:

for initialization; condition; post {
    // Some tasks to do
}

This loop does the following:

  • First, the initialization is executed,
  • Then, while the condition is true, we keep executing the tasks inside the loop body,
  • After each iteration, post is executed, which changes the state in some way.

Now, let's illustrate this with a code snippet that prints numbers 1 through 5:

for i := 1; i <= 5; i++ {
    // The following command will print the number i
    fmt.Println(i)
}
// Prints:
// 1
// 2
// 3
// 4
// 5

Here, we define an int variable i, assign 1 to it first, then repeatedly execute fmt.Println(i) while i is less than or equal to 5, incrementing i by 1 after every iteration. The operation i++ simply adds 1 to the current value of i, and this operation is known as increment.

Using the Range Clause in Go: Part 1

In Go, the range clause is used to loop through items in a data structure such as an array, slice, string, map, or channel. Imagine you're playing a game in which you have to try and spot certain shapes within an image. In this task, you would go through the entire image once. The range clause operates in a similar fashion!

Here's an example of printing all the elements of an array:

numbers := []int{5, 4, 3, 2, 1}

// The loop below will take each element num from numbers and print it and its index
for index, num := range numbers {
    fmt.Println("element at index", index, "equals" num)
}
// Prints:
// element at index 0 equals 5
// element at index 1 equals 4
// element at index 2 equals 3
// element at index 3 equals 2
// element at index 4 equals 1
Using the Range Clause in Go: Part 2
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