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.
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
initializationis executed, - Then, while the
conditionis true, we keep executing thetasksinside the loop body, - After each iteration,
postis 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.
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:
