go · level 1 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Walk through the slice and check every item.
To a slice, walk through it and check each item with an if. Picture looking for your friend in a crowd, one face at a time.
Keep a : a bool box that starts as false. When you spot a match, set it to true. You can also break there, since there is no need to keep looking.
The same walk finds the biggest item. Start with the first item as the best so far. Whenever an item beats it, that item becomes the new best.
package main
import "fmt"
func main() {
guests := []string{"Ava", "Ben", "Cleo"}
found := false
for _, guest := range guests {
if guest == "Ben" {
found = true
}
}
fmt.Println("Is Ben coming?", found)
} To find the smallest instead, swap > for < when you compare.
guess first
Best so far. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
scores := []int{4, 9, 7}
best := scores[0]
for _, score := range scores {
if score > best {
best = score
}
}
fmt.Println(best)
}
your turn
Your turn. Check the shopping basket.
Type one of the items in the basket between the quotes, spelled exactly the same, so the search finds it.
output
press run to see what happens
fix it
That is not the cheapest price. Fix it!
output
press run to see what happens
- The program says 8, the biggest price. Look at the comparison inside the
if. - To find the cheapest, swap in any price that is smaller than the best so far.
- Change
>to<on line 7, then press run.
nailed it
you can find anything in a slice. :D
- Search by walking through a slice with an
if. - A
boolflag remembers whether you found a match. - Keep a best-so-far box to find the biggest.
new words in your collection
- search
- flag
This lesson isn’t saved. A free account remembers every lesson you finish.