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:

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:

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:

Using the Range Clause in Go: Part 2

Sometimes, you don't need an index; you want to use only the elements themselves. In this case, it is common to use _ variable name instead of index, thus indicating that we are not going to use this variable. Here is an example:

Difference Between the Basic For Loop and the Range Clause

You would typically use a basic for loop when you need to perform a task a certain number of times. The range clause, on the other hand, is your go-to option for iterating over collections (like an array, slice, or map) and executing an action for each item.

Let's illustrate with both methods printing numbers from a slice:

Basic for loop:

Range clause:

Lesson Summary

Well done, Explorer! You've mastered the Go for loop and range clause! Now, you can loop over arrays or slices in the same way as you go through the pages of a book! Practice using these tools to reinforce your understanding and prepare for the next lesson. Let's explore further into the exciting world of Go programming! Happy coding!

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