check if a channel is buffered in go

To check if a channel is buffered, you can use the built-in len and cap functions. len returns the number of elements currently buffered in the channel, and cap returns the capacity of the buffer.

If the length of the channel is equal to its capacity, then the channel is fully buffered. If the length is less than the capacity, then the channel is partially buffered.

Here's an example:

main.go
ch := make(chan int, 5)  // create buffered channel with capacity 5

fmt.Println(len(ch))    // prints 0
fmt.Println(cap(ch))    // prints 5

ch <- 1                  // send a value to the channel
fmt.Println(len(ch))    // prints 1
fmt.Println(cap(ch))    // prints 5

ch <- 2                  // send another value to the channel
fmt.Println(len(ch))    // prints 2
fmt.Println(cap(ch))    // prints 5
405 chars
13 lines

In this example, we create a buffered channel of type int with capacity 5. We then check the length and capacity of the channel using len and cap. Initially, the length of the channel is 0 because there are no values in the buffer. After sending two values to the channel, the length becomes 2 and the capacity remains 5.

gistlibby LogSnag