Lesson 1

Mastering Loops in Go: Exploring `for` and `range`

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:

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

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:

1for i := 1; i <= 5; i++ { 2 // The following command will print the number i 3 fmt.Println(i) 4} 5// Prints: 6// 1 7// 2 8// 3 9// 4 10// 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:

1numbers := []int{5, 4, 3, 2, 1} 2 3// The loop below will take each element num from numbers and print it and its index 4for index, num := range numbers { 5 fmt.Println("element at index", index, "equals" num) 6} 7// Prints: 8// element at index 0 equals 5 9// element at index 1 equals 4 10// element at index 2 equals 3 11// element at index 3 equals 2 12// element at index 4 equals 1
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:

1numbers := []int{5, 4, 3, 2, 1} 2for _, num := range numbers { 3 fmt.Println(num) 4}
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:

1// This loop will print all numbers from the numbers slice using its indices 2numbers := []int{1, 2, 3, 4, 5} 3 4// `i` goes through all slice indices - 0, 1, 2, ..., len(numbers) - 1 5for i := 0; i < len(numbers); i++ { 6 fmt.Println(numbers[i]) 7} 8// Prints: 9// 1 10// 2 11// 3 12// 4 13// 5

Range clause:

1// This loop will print all numbers from the numbers slice, directly taking each of them 2numbers := []int{1, 2, 3, 4, 5} 3 4for _, num := range numbers { 5 fmt.Println(num) 6} 7// Prints: 8// 1 9// 2 10// 3 11// 4 12// 5
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!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.