go · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
walks through a slice, one item at a time.
for i, snack := range snacks { walks through a slice, one item per round. Each time, i holds the index and snack holds the item. Picture ticking off a shopping list, line by line.
Go insists you use every box you declare. If you only need the item, put the _ in place of i: for _, snack := range snacks {.
To add things up, keep a . Make a box holding 0 before the loop, then add each item to it inside the loop.
package main
import "fmt"
func main() {
prices := []int{3, 5, 2}
total := 0
for _, price := range prices {
total = total + price
}
fmt.Println("Total:", total)
} Read for _, price := range prices as "for each price in prices".
guess first
Index and item together. What appears?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
pets := []string{"cat", "dog"}
for i, pet := range pets {
fmt.Println(i, pet)
}
}
your turn
Your turn. Add up your scores.
Type three whole-number scores between the commas. The loop adds them into a running total for you.
output
press run to see what happens
fix it
Go refuses to run this loop. Can you fix it?
output
press run to see what happens
- Read the error. Which box does Go say is declared but not used?
- The loop never uses i, the index. Go wants every box used.
- Put the blank identifier _ in place of i on line 5, then press run.
nailed it
you visited every item in a slice. :D
for i, item := range svisits every item.- Use
_for a value you do not need. - Build a running total in a box that starts at 0.
new words in your collection
- range
- blank identifier
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.