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")
}
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...
