Buffered Channels
Standard channels are unbuffered (capacity 0). You can create buffered channels by providing a capacity as the second argument to make.
Syntax
ch := make(chan string, 3)
Behavior
- Saves Data: A buffered channel can hold up to its capacity without requiring an immediate receiver.
- Non-blocking Sends: Sending to a buffered channel only blocks when the buffer is full.
- Non-blocking Receives: Receiving from a buffered channel only blocks when the buffer is empty.
Use Case: Batching
Buffered channels are ideal for batching tasks or decoupling producers and consumers where the processing speeds might fluctuate.
ch := make(chan int, 100)
for i := 0; i < 100; i++ {
ch <- i // These 100 sends won't block
}