Start learning free

LESSON 139 OF 671 · FOR LOOPS - LOOPING OVER ARRAYS

For Loops in Go

Lesson

A for loop is a special type of loop in Go which allows us to loop over the items of a collection, such as a string or an array.


Looping through a string:

For example, a string is a sequence of characters, so we can use a for loop to iterate over each character and do something with that character:

name := "Andy"

for _, letter := range name {
  fmt.Println(string(letter))
}

Let's break down this code:

  • The for keyword that indicates the start of a for loop.
  • _, letter declares the loop variables: _ discards the index, and letter takes the value of each different item in the collection (for a string, each character as a rune)
  • The range keyword iterates over the collection we will iterate on
  • name is the collection to loop over

The output of this code is:

A
n
d
y

As you can see, on each iteration, letter was assigned the value of the next item in the string and inside the loop, we printed that value.


Looping through an array:

We can also use for loops with slices:

fruits := []string{"banana", "orange", "pear", "kiwi"}

for _, fruit := range fruits {
  fmt.Println("I eat " + fruit)
}

The output of this code is:

I eat banana
I eat orange
I eat pear
I eat kiwi

Assignment
Now let's greet our friends using a for loop!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check