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:
