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 }
More Related questions...