Channels in Go – Buffered, Unbuffered, and Select Statement
What is a Channel?
A channel is a typed conduit used to send and receive values between goroutines, enabling safe communication without explicit locks.
Unbuffered Channels
ch := make(chan int)
go func() {
ch <- 42 // sends value, blocks until received
}()
value := <-ch // receives value
fmt.Println(value)
Buffered Channels
ch := make(chan int, 3) // capacity of 3
ch <- 1
ch <- 2
ch <- 3
// sending a 4th value would block until space is available
The select Statement
select lets a goroutine wait on multiple channel operations, proceeding with whichever is ready first.
select {
case msg1 := <-ch1:
fmt.Println("Received:", msg1)
case msg2 := <-ch2:
fmt.Println("Received:", msg2)
default:
fmt.Println("No message ready")
}
PreviousConcurrency in Go – Goroutines and Sync.WaitGroup Tutorial
Next How to Build a REST API in Go using net/http – Complete CRUD
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)