Challenge - 5 Problems
Channel Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Go code using channels?
Consider the following Go program. What will it print when run?
Go
package main import "fmt" func main() { ch := make(chan int) go func() { ch <- 42 }() val := <-ch fmt.Println(val) }
Attempts:
2 left
💡 Hint
Think about how the goroutine sends a value and the main goroutine receives it.
✗ Incorrect
The anonymous goroutine sends 42 into the channel ch. The main goroutine receives it and prints 42.
❓ Predict Output
intermediate2:00remaining
What happens if you try to receive from a closed channel?
What will this Go program print?
Go
package main import "fmt" func main() { ch := make(chan int, 1) ch <- 10 close(ch) val1, ok1 := <-ch val2, ok2 := <-ch fmt.Println(val1, ok1) fmt.Println(val2, ok2) }
Attempts:
2 left
💡 Hint
Remember what happens when you receive from a closed channel with buffered values.
✗ Incorrect
The first receive gets the buffered value 10 and ok is true. The second receive gets zero value 0 and ok is false because channel is closed and empty.
🔧 Debug
advanced2:00remaining
Why does this Go program deadlock?
Examine the code below. Why does it cause a deadlock?
Go
package main func main() { ch := make(chan int) ch <- 5 val := <-ch println(val) }
Attempts:
2 left
💡 Hint
Think about how unbuffered channels block on send and receive.
✗ Incorrect
The send operation blocks because no goroutine is ready to receive from the unbuffered channel, causing deadlock.
🧠 Conceptual
advanced1:30remaining
What is the effect of closing a channel in Go?
Which statement about closing a channel is true?
Attempts:
2 left
💡 Hint
Think about how receivers can check if a channel is closed.
✗ Incorrect
Closing a channel signals receivers that no more values will come, allowing them to stop receiving gracefully.
❓ Predict Output
expert3:00remaining
What is the output of this Go program with multiple goroutines and channels?
Analyze the code and select the correct output.
Go
package main import ( "fmt" "sync" ) func main() { ch := make(chan int) var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() for i := 0; i < 3; i++ { ch <- i } }() go func() { defer wg.Done() for i := 3; i < 6; i++ { ch <- i } }() go func() { wg.Wait() close(ch) }() sum := 0 for v := range ch { sum += v } fmt.Println(sum) }
Attempts:
2 left
💡 Hint
Consider the values sent on the channel and how the sum is calculated.
✗ Incorrect
The two goroutines send values 0 to 2 and 3 to 5, total sum is 0+1+2+3+4+5=15.