check if a channel is not full in go

Here's a simple code snippet to check if a channel is not full using the select statement in Go:

main.go
func isChannelNotFull(ch chan int) bool {
    select {
    case ch <- 1:
        // channel is not full, put the value in and return true
        return true
    default:
        // channel is full, discard the value and return false
        return false
    }
}
263 chars
11 lines

In this code, a select statement is used to try to put a value in the channel. If the channel is not full, the value is put in and the function returns true. If the channel is full, the default case is triggered, the value is discarded, and the function returns false.

Note that the <- operator is used with the channel to receive a value from the channel, while the -> operator is used to put a value into the channel. By using the ch <- 1 syntax, we are attempting to put a value into the channel without blocking. If the channel is full, this will not be possible and the default case will be triggered.

gistlibby LogSnag