Loop Over a Slice and Count Matches in Go
Scenario
Check the Go slice version of countOpenRooms on identical contract fixtures.
func countOpenRooms(seatCounts []int) int {
openRooms := 0
for _, seats := range seatCounts {
if seats > 0 {
openRooms++
}
}
return openRooms
}Try it yourself
Compare each Go case and notice how the blank identifier _ keeps the loop concise.
| Case | Result |
|---|---|
| countOpenRooms([]int{}) | Select a choice above to see what happens. |
| countOpenRooms([]int{1}) | Select a choice above to see what happens. |
| for _, seats := range seatCounts vs for seats := range seatCounts | Select a choice above to see what happens. |
Reveal the explanation
- countOpenRooms([]int{})
0 — identical to Python and JavaScript.
- countOpenRooms([]int{1})
1 — identical to Python and JavaScript.
- for _, seats := range seatCounts vs for seats := range seatCounts
Single variable in Go range gets the INDEX (0, 1, 2), NOT the value! Always use _, seats.
The most common beginner bug in Go is writing "for seats := range seatCounts", which reads indices instead of seat counts. Always use "_, seats" when you want values.
Download shared test cases
Your turn
Write countPassing(scores []int) int in Go using range and state what happens if you omit the underscore _.
Common mistake Writing "for score := range scores" and accidentally testing index >= 60 instead of score >= 60.
Check your work
for _, score := range scores { if score >= 60 { passed++ } }.
Quick check
This browser could not save your progress. Changes last until you leave the page.