TL ; DR:
slices.Contains(s, x) is true when the slice holds x, and false when it doesn't. Use it as the condition of an if.
colors := []string{"red", "green", "blue"}
fmt.Println(slices.Contains(colors, "red")) // true
fmt.Println(slices.Contains(colors, "pink")) // false
if !slices.Contains(colors, "pink") {
fmt.Println("No pink yet")
}
Full lesson:
Often you need to know if a slice holds some value. Is this name on the guest list? Is this item in the cart?
slices.Contains(s, x) answers that. It comes from the slices package you met in the last lesson.
It compares each item with x, from the first one on. It returns true as soon as one matches, or false if none does.
Put ! in front for the opposite. So !slices.Contains(s, x) is true when x is missing.
The answer is a bool, so it fits right into an if:
cart := []string{"milk", "bread"}
if slices.Contains(cart, "milk") {
fmt.Println("Milk is in the cart")
}
Go has no in keyword for slices. Before Go 1.21, people wrote a loop for this.
Text must match exactly. So slices.Contains(colors, "Red") is false, because the slice has "red".
Your task
bag holds what is packed for a hike.
If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.
Expected output:
Water is packed
Pack a tentFree plan: 30 tutor messages. PRO is unlimited.
