~/Golang Channel Buffer Overview

Jul 15, 2022


Golang channels can be either buffered or unbuffered. A channel in Go allows goroutines to communicate and synchronize execution.

Buffered channels have a capacity. Sending to a full channel blocks until space is available. Receiving from an empty channel blocks until data is available.

Create a buffered channel:

1
ch := make(chan int, 3) // capacity 3

Check the buffer length and capacity with len(ch) and cap(ch).

Example:

1
2
3
4
5
6
7
ch := make(chan string, 2)
ch <- "a"
ch <- "b"
// ch <- "c" // blocks, buffer is full

fmt.Println(<-ch) // "a"
ch <- "c" // succeeds now

Buffered channels are useful for rate-limiting, pipelining, or when coordination between goroutines is needed without blocking for every message.

Unbuffered channels have a zero buffer size and block on every send and receive until the other side is ready.

For details, see the Go specification on channels.

Tags: [golang] [channel]