Curriculum

Curriculum

Loop Over a Slice and Count Matches in Go

Scenario

Check the Go slice version of countOpenRooms on identical contract fixtures.

Selected choicePick a choice below
Result—
Go
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.

Reveal the explanation
  1. countOpenRooms([]int{})

    0 — identical to Python and JavaScript.

  2. countOpenRooms([]int{1})

    1 — identical to Python and JavaScript.

  3. 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.

Review first
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

In Go, what does "for x := range []int{50, 90}" assign to x?
Show the answer and reasoning

Correct answer The indices 0 and 1 (not 50 and 90)

In Go, a single range variable always receives the index; use _, x to receive the value.