0
0
Goprogramming~20 mins

Why channels are used in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Channel Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
AEmpty output
BCompilation error
CHello from goroutine
DDeadlock error at runtime
Attempts:
2 left
💡 Hint
Think about how channels allow communication between goroutines.
🧠 Conceptual
intermediate
1:30remaining
Why are channels important in Go concurrency?
Why do Go programmers use channels when working with goroutines?
ATo share memory safely by passing messages
BTo replace functions with asynchronous calls
CTo create new goroutines automatically
DTo speed up the program by avoiding all synchronization
Attempts:
2 left
💡 Hint
Think about how channels help avoid data races.
Predict Output
advanced
1: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
}
ACompilation error: cannot send on nil channel
BProgram deadlocks and panics at runtime
CProgram prints 5
DProgram exits silently
Attempts:
2 left
💡 Hint
A nil channel blocks forever on send or receive.
🔧 Debug
advanced
2: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)
}
ABecause the channel buffer is full
BBecause the channel is nil
CBecause the channel is closed before sending
DBecause the send blocks waiting for a receiver that is not ready
Attempts:
2 left
💡 Hint
Think about how unbuffered channels block on send and receive.
🚀 Application
expert
2: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))
}
A2
B1
C3
D0
Attempts:
2 left
💡 Hint
Remember that reading from the channel removes one item from the buffer.