Go Tutorial: Loops
Stop repeating yourself. Teach your program to repeat things for you.
Why write it 100 times when Go can do it for you
Imagine you need to print the numbers 1 to 100. You could write 100 `fmt.Println` lines. Or you could write a loop and let Go do the counting.
Loops are one of the most powerful things in programming. Once you get them, a huge amount of what computers are actually doing starts to make sense.
Twelve steps. Let's go.
What you'll learn in this Go loops tutorial
This interactive Go tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Your first loop — A loop repeats an action. Write the action once, tell it how many times.
- Loop over a slice with range — Use `for i, book := range books` to loop over every item in a slice. `i` is the index, `book` is the value.
- Skip the index with _ — Sometimes you only want the value, not the index. Use `_` to ignore it.
- Loop over a map — Maps and range work together. `for isbn, title := range catalog` gives you every key-value pair.
- Break out early — Use `break` to exit a loop immediately. When you find what you need, stop searching.
- Running total 🤯 — A loop can accumulate a result. This is called a running total.
- Continue — skip the rest of this iteration — `continue` skips the current iteration and moves to the next one. Use it to filter.
- Nested loops — loop inside a loop — A loop inside another loop creates combinations. For each shelf, print 3 books.
Go Loops concepts covered
- Why write it 100 times when Go can do it for you