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 12 hands-on exercises. Estimated time: 18 minutes.
- Your first loop — Think about a washing machine. You do not press "wash" 10 times for 10 items of clothing. You load everything, press sta…
- The three parts of a for loop — A `for` loop has three parts separated by semicolons:
- Use the counter inside the loop — `i` is just a variable. You can use it inside the loop body — multiply it, add to it, print it in a sentence.
- Counting down — Loops do not have to count up. Change the step and direction and they count down.
- while-style loop — Go has no `while` keyword. But a `for` loop without the start and step parts behaves exactly like a while loop — it runs…
- Infinite loop with break — `for { }` with no condition runs forever. That sounds terrifying, but it is actually useful — when you do not know in ad…
- continue — skip and keep going — `continue` skips the rest of the current iteration and jumps straight to the next one. The loop keeps running — just not…
- Nested loops — a loop inside a loop — You can put a loop inside another loop. The inner loop runs completely for every single iteration of the outer loop.
- Running total — One of the most common loop patterns: start a variable at zero, add to it inside the loop, read the result after.
- range — cleaner counting — When you just want to count a fixed number of times, `range` is a cleaner option.
- Fix the infinite loop — This program is supposed to print numbers until it reaches 10 — but it runs forever and never stops.
- Build a countdown — No starter code.
Go Loops concepts covered
- Why write it 100 times when Go can do it for you