check if a channel is full in go

main.go
func main() {
    ch := make(chan int, 3)
    ch <- 1
    ch <- 2
    ch <- 3

    select {
    case ch <- 4:
        fmt.Println("Channel has room for more values.")
    default:
        fmt.Println("Channel is full, can't accept more values.")
    }
}
254 chars
14 lines

In Go, you can check if a channel is full by using the select statement with a default clause. The default clause is selected when none of the other cases are ready, and in this case it is used to detect if the channel is full.

In the example above, a buffered channel is created with a capacity of 3 (i.e., it can hold up to 3 values). The channel is then filled with 3 values, which means it is now full. The select statement is then used to check if there is room for another value in the channel. The case ch <- 4: attempts to add another value to the channel. If the channel is not full, the value will be added, and the fmt.Println("Channel has room for more values.") statement will be printed. Otherwise, the default clause will be selected, and the fmt.Println("Channel is full, can't accept more values.") statement will be printed.

gistlibby LogSnag