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 program using channels?
Consider this Go code that uses a channel to communicate between goroutines. What will it print?
Go
package main import ( "fmt" ) func main() { ch := make(chan string) go func() { ch <- "Hello from goroutine" }() msg := <-ch fmt.Println(msg) }
Attempts:
2 left
💡 Hint
Think about how channels allow communication between goroutines.
✗ Incorrect
The goroutine sends a string to the channel, and the main goroutine receives it and prints it. This is the main use of channels: safe communication between goroutines.
🧠 Conceptual
intermediate1:30remaining
Why are channels important in Go concurrency?
Why do Go programmers use channels when working with goroutines?
Attempts:
2 left
💡 Hint
Think about how channels help avoid data races.
✗ Incorrect
Channels allow goroutines to communicate by sending and receiving values, which helps avoid sharing memory directly and prevents data races.
❓ Predict Output
advanced1:30remaining
What happens if you send on a nil channel?
Look at this Go code snippet. What will happen when it runs?
Go
package main func main() { var ch chan int ch <- 5 }
Attempts:
2 left
💡 Hint
A nil channel blocks forever on send or receive.
✗ Incorrect
Sending on a nil channel blocks forever, causing a deadlock and runtime panic.
🔧 Debug
advanced2:00remaining
Why does this Go program deadlock?
This Go program uses a channel but deadlocks. Why?
Go
package main import "fmt" func main() { ch := make(chan int) ch <- 10 fmt.Println(<-ch) }
Attempts:
2 left
💡 Hint
Think about how unbuffered channels block on send and receive.
✗ Incorrect
Unbuffered channels block the sender until a receiver is ready. Here, the send happens before any receiver, causing deadlock.
🚀 Application
expert2:30remaining
How many items are in the channel buffer after this code runs?
Given this Go code, how many items remain in the channel buffer after execution?
Go
package main import "fmt" func main() { ch := make(chan int, 3) ch <- 1 ch <- 2 ch <- 3 <-ch ch <- 4 fmt.Println(len(ch)) }
Attempts:
2 left
💡 Hint
Remember that reading from the channel removes one item from the buffer.
✗ Incorrect
The channel buffer size is 3. After sending 3 items, one is received (removed), then one more is sent. The buffer holds 2 items after execution.