As well as the type that is traveling through the channel, there is another property that the channel has: its capacity. This represents the number of items a channel can hold before any new attempt to send an item is made, resulting in a blocking operation. The capacity of the channel is decided at its creation and its default value is 0:
// channel with implicit zero capacity
var a = make(chan int)
// channel with explicit zero capacity
var a = make(chan int, 0)
// channel with explicit capacity
var a = make(chan int, 10)
The capacity of the channel cannot be changed after its creation and can be read at any time using the built-in cap function:
func main() {
var (
a = make(chan int, 0)
b = make(chan int, 5)
)
fmt.Println("a is", cap(a))
fmt.Println("b is", cap(b))
}
The full example is available at https://play.golang.org/p/Yhz4bTxm5L8.
The len function, when used on a channel, tells us the number of elements that are held by the channel:
func main() {
var (
a = make(chan int, 5)
)
for i := 0; i < 5; i++ {
a <- i
fmt.Println("a is", len(a), "/", cap(a))
}
}
The full example is available at https://play.golang.org/p/zJCL5VGmMsC.
From the previous example, we can see how the channel capacity remains as 5 and the length grows with each element.