×

go · level 1 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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".