Buffered and unbuffered channels
Buffered and unbuffered channels
A channel is a typed communication path between goroutines. Create one with make(chan T) for an unbuffered channel or make(chan T, n) for a buffer of n elements. An unbuffered send needs a matching receiver; a buffered send can finish while space remains. The channel value can be passed to another function without copying its queued elements.
package main
import ( "fmt")
func main() { ch := make(chan int) go func() { ch <- 42 }() fmt.Println(<-ch)}The arrow points toward the destination: ch <- 42 sends; <-ch receives. The receiver and sender rendezvous. This example needs no sleep or polling. The send transfers an int, not a reference to the sender’s variable.
Expected output:
42Queue two values
package main
import ( "fmt")
func main() { ch := make(chan string, 2) ch <- "red" ch <- "blue" fmt.Println(len(ch), cap(ch)) fmt.Println(<-ch, <-ch)}Both sends fit before the first receive. A channel is FIFO for sequential sends from one producer; do not infer a global producer ordering from this. len is the number queued at that instant and cap is the buffer capacity. A third send here would block until a receiver frees space.
Expected output:
2 2red blueTry it locally
Create a channel with capacity three, send 4, 5, 6, then print its capacity and the sum of three receives.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Channels 01: Buffered and unbuffered channels
Check the lesson objective before moving on.
What does make(chan int, 2) allocate?
When can an unbuffered send complete?