TryBugHunt
goInfinite loopMedium

Deadlock in range loop over unclosed channel

BugFind the bug and fix the code

What it should do

Drain all queued integers from a channel into a slice. Example: drainTaskQueue(3) -> [1, 2, 3]

What happens instead

fatal error: all goroutines are asleep - deadlock!

package main

import "fmt"

func drainTaskQueue(n int) []int {
	ch := make(chan int, n)
	for i := 1; i <= n; i++ {
		ch <- i
	}
	var res []int
	for val := range ch {
		res = append(res, val)
	}
	return res
}

func main() {
	fmt.Println(drainTaskQueue(3))
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

A medium Go debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: A for ... range loop over a channel continues waiting for items until the channel is explicitly closed. Because ch was never closed, the loop blocked after draining elements, deadlocking.

The fix: Call close(ch) before beginning the for ... range loop over the channel.

Remember: Senders must close channels when no more values will be produced, so receivers know when iteration terminates.

The pattern behind it: infinite loops.

More infinite loops to practise

Seen this error in your own code?

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/01017062-1599-4d01-83f7-7ce4ea163e72" title="Debugging challenge: Deadlock in range loop over unclosed channel" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/01017062-1599-4d01-83f7-7ce4ea163e72">TryBugHunt</a></p>