Golang / GoLang Concurrency Mastery Interview Questions
What are directional channels in Go and why use them in function signatures?
Go channels can be typed with a direction: chan<- T (send-only) or <-chan T (receive-only). A bidirectional chan T can be assigned to either. Directional channels enforce access discipline at compile time, making the data-flow contract of each function explicit.
// Producer: only sends to out — compile error if it tries to receive
func produce(out chan<- int) {
for i := 0; i < 5; i++ { out <- i }
close(out) // close is allowed on a send-only channel
// v := <-out // COMPILE ERROR: receive from send-only channel
}
// Consumer: only receives from in
func consume(in <-chan int) {
for v := range in { fmt.Println(v) }
// in <- 99 // COMPILE ERROR: send to receive-only channel
// close(in) // COMPILE ERROR: close of receive-only channel
}
// Bidirectional channel can be passed as either direction
ch := make(chan int, 10) // chan int (bidirectional)
go produce(ch) // narrowed to chan<- int automatically
consume(ch) // narrowed to <-chan int automatically
// Pipeline: each stage returns receive-only — caller can't accidentally close
func generator(nums ...int) <-chan int {
out := make(chan int)
go func() { defer close(out); for _, n := range nums { out <- n } }()
return out // exposes only read access
}
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() { defer close(out); for v := range in { out <- v * v } }()
return out
}
for v := range square(generator(2, 3, 4)) {
fmt.Println(v) // 4 9 16
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
