Golang / GoLang Basics Interview Questions
What are channels in Go and what is the difference between buffered and unbuffered?
Channels are typed conduits for sending values between goroutines. They are goroutine-safe and provide the synchronisation primitive underlying Go's concurrency model. Go's philosophy: "Do not communicate by sharing memory; instead, share memory by communicating."
// Unbuffered channel â send BLOCKS until a receiver is ready ch := make(chan int) go func() { ch <- 42 }() // goroutine parks until main receives v := <-ch // unblocks sender fmt.Println(v) // 42 // Buffered channel â send blocks only when buffer is FULL buf := make(chan string, 3) buf <- "a" // no goroutine needed â goes into buffer buf <- "b" fmt.Println(<-buf) // a (FIFO) fmt.Println(<-buf) // b // Closing a channel signals: no more values will be sent jobs := make(chan int, 5) for i := 0; i < 5; i++ { jobs <- i } close(jobs) // Range â exits automatically when channel is closed and drained for j := range jobs { fmt.Println(j) } // 0 1 2 3 4 // Comma-ok: detect closed channel val, ok := <-jobs fmt.Println(val, ok) // 0 false // select â wait on multiple channel operations select { case v := <-ch1: fmt.Println("ch1:", v) case v := <-ch2: fmt.Println("ch2:", v) case <-time.After(time.Second): fmt.Println("timeout") }
More Related questions...