GO Channels and Communication 2 — Questions and Answers
Question 1: What is a directional channel type in Go?
- A channel with a fixed direction in memory
- A channel restricted to send-only or receive-only operations (Correct answer)
- A channel that sends in order
- A bidirectional buffered channel
Correct answer: A channel restricted to send-only or receive-only operations
Directional channels like `chan<- int` (send-only) and `<-chan int` (receive-only) restrict operations for safer API design.
Question 2: What does `select { case <-ch: default: }` do?
- Blocks until ch receives
- Performs a non-blocking receive from ch (Correct answer)
- Closes ch if empty
- Drains all values from ch
Correct answer: Performs a non-blocking receive from ch
A `select` with a `default` case performs a non-blocking operation; if no case is ready, `default` executes immediately.
Question 3: Which channel declaration creates an unbuffered channel of strings?
- var ch chan string
- ch := make(chan string)
- ch := make(chan string, 0)
- Both B and C (Correct answer)
Correct answer: Both B and C
Both `make(chan string)` and `make(chan string, 0)` create unbuffered channels; `var ch chan string` declares a nil channel.
Question 4: What is a nil channel's behavior when read from or written to?
- Panics immediately
- Blocks forever (Correct answer)
- Returns zero value
- Causes compile error
Correct answer: Blocks forever
Both sends and receives on a nil channel block forever, which can be used intentionally to disable a select case.
Question 5: How can you implement a timeout for a channel receive in Go?
- Use time.Sleep before receiving
- Use select with a time.After case (Correct answer)
- Use ch.Timeout(d)
- Use context.Deadline only
Correct answer: Use select with a time.After case
`select { case v := <-ch: ... case <-time.After(d): ... }` implements a receive timeout by racing the channel against a timer channel.
Question 6: What is the fan-out concurrency pattern in Go?
- One goroutine reads from multiple channels
- One input channel is read by multiple goroutines in parallel (Correct answer)
- Multiple channels merge into one
- Goroutines share a single mutex
Correct answer: One input channel is read by multiple goroutines in parallel
Fan-out distributes work by having multiple goroutines read from a single input channel, processing jobs in parallel.
What is a directional channel type in Go?