GO Channels and Communication 3 — Questions and Answers
Question 1: What is the fan-in concurrency pattern?
- One goroutine writes to many channels
- Multiple channels are merged into one output channel (Correct answer)
- A channel is read in a loop
- Channels are nested inside structs
Correct answer: Multiple channels are merged into one output channel
Fan-in merges multiple input channels into a single output channel, typically using a goroutine per input channel that forwards values.
Question 2: How do you check if a channel receive returned a real value or a closed-channel zero value?
- v == nil
- v, ok := <-ch; check ok (Correct answer)
- len(ch) > 0
- cap(ch) > 0
Correct answer: v, ok := <-ch; check ok
The two-value receive `v, ok := <-ch` sets `ok` to `false` when the channel is closed and all buffered values have been received.
Question 3: What does `len(ch)` return for a buffered channel?
- Channel capacity
- Number of elements currently buffered (Correct answer)
- Number of goroutines waiting to send
- Always 0
Correct answer: Number of elements currently buffered
`len(ch)` returns the number of elements currently queued (unread) in the channel's buffer.
Question 4: What is a done channel pattern used for?
- Limit channel buffer size
- Signal goroutines to stop working and exit (Correct answer)
- Synchronize goroutine start times
- Measure goroutine performance
Correct answer: Signal goroutines to stop working and exit
A done channel (typically `chan struct{}`) is closed to broadcast a cancellation signal to multiple goroutines watching it.
Question 5: Why is `chan struct{}` preferred over `chan bool` for signaling in Go?
- struct{} has faster sends
- struct{} consumes zero bytes, minimizing memory overhead (Correct answer)
- bool channels do not support close
- struct{} channels are unbuffered by default
Correct answer: struct{} consumes zero bytes, minimizing memory overhead
`struct{}` is an empty type with zero size, so a `chan struct{}` uses no memory for the values themselves, making it the most efficient signal channel.
Question 6: What is a pipeline pattern in Go?
- Chaining functions without channels
- A series of stages connected by channels, each processing and passing data (Correct answer)
- A single goroutine processing a list
- Parallel sorting of a slice
Correct answer: A series of stages connected by channels, each processing and passing data
A Go pipeline is a series of stages where each stage receives values from upstream via a channel, processes them, and sends results to the next stage via another channel.
What is the fan-in concurrency pattern?