check if a channel is not empty in go

To check if a channel is not empty in Go, we can use the select statement to perform a non-blocking read on the channel. If the channel is not empty, the value will be read and the corresponding case will be executed. Otherwise, the default case will be executed.

main.go
func isChannelNotEmpty(ch chan int) bool {
    select {
    case <-ch:
        // channel is not empty
        return true
    default:
        // channel is empty
        return false
    }
}
193 chars
11 lines

In the above code, we define a function isChannelNotEmpty that takes a channel ch as input and returns a boolean indicating whether the channel is not empty. Inside the function, we use the select statement with two cases.

The first case checks if a value can be read from the channel using <-ch. If a value is present, the case is executed and the function returns true.

The default case is executed if the channel is empty. In this case, the function returns false.

We can use this function to check if a channel is not empty before attempting to read from it in a blocking manner.

gistlibby LogSnag