Challenge - 5 Problems
Go Blocking Master
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 with channels?
Consider the following Go code. 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 channels block until data is sent or received.
✗ Incorrect
The goroutine sends 42 into the channel. The main goroutine waits to receive from the channel, so it blocks until the value is sent. Then it prints 42.
❓ Predict Output
intermediate2:00remaining
What happens when reading from a closed channel?
What will this Go program print?
Go
package main import "fmt" func main() { ch := make(chan int) close(ch) val, ok := <-ch fmt.Println(val, ok) }
Attempts:
2 left
💡 Hint
Reading from a closed channel returns zero value and false.
✗ Incorrect
When a channel is closed, receiving from it returns the zero value of the channel type and false for the second value.
❓ Predict Output
advanced2:00remaining
What is the output of this select with blocking channels?
Analyze the following Go code and determine its output.
Go
package main import ( "fmt" "time" ) func main() { ch1 := make(chan string) ch2 := make(chan string) go func() { time.Sleep(100 * time.Millisecond) ch1 <- "first" }() go func() { time.Sleep(50 * time.Millisecond) ch2 <- "second" }() select { case msg1 := <-ch1: fmt.Println(msg1) case msg2 := <-ch2: fmt.Println(msg2) } }
Attempts:
2 left
💡 Hint
Which channel sends first after the sleep?
✗ Incorrect
ch2 sends after 50ms, ch1 after 100ms. The select receives from the first ready channel, so it prints "second".
❓ Predict Output
advanced2:00remaining
What error does this Go program produce?
What happens when you run this Go code?
Go
package main func main() { ch := make(chan int) ch <- 1 }
Attempts:
2 left
💡 Hint
Sending on an unbuffered channel blocks until another goroutine receives.
✗ Incorrect
The main goroutine tries to send on ch but no other goroutine receives, so it blocks forever and causes a deadlock panic.
🧠 Conceptual
expert2:00remaining
How many items are in the buffered channel after this code runs?
Given the following Go code, how many items remain in the channel after execution?
Go
package main import "fmt" func main() { ch := make(chan int, 3) ch <- 10 ch <- 20 <-ch ch <- 30 fmt.Println(len(ch)) }
Attempts:
2 left
💡 Hint
Remember that reading from the channel removes an item.
✗ Incorrect
Two items remain because one was removed by the receive operation, so the channel holds 2 items.