Channel Buffering
By default, channels are unbuffered, meaning that they will only accept a send if there is a corresponding receive ready to take the value. Buffered channels accept a limited number of values without a corresponding receiver for those values.
Key Points
- By default, channels are unbuffered.
- Unbuffered channels require a sender and receiver to be ready at the same time.
- Buffered channels have a capacity and can store a limited number of values without a corresponding receiver.
make(chan T, capacity)creates a buffered channel.- Sends to a buffered channel block only when the buffer is full. Receives block only when the buffer is empty.
Buffered Channel Example
This example shows a buffered channel with a capacity of 2.
package main
import "fmt"
func main() {
messages := make(chan string, 2)
messages <- "buffered"
messages <- "channel"
fmt.Println(<-messages)
fmt.Println(<-messages)
}buffered
channelChannel Types
| Type | Syntax | Behavior |
|---|---|---|
| Unbuffered | make(chan T) | Synchronous; sender and receiver must be ready. |
| Buffered | make(chan T, N) | Asynchronous; can hold N values before blocking. |