check if a channel is closed in go

In Go, you can check if a channel is closed by using a select statement with the default case. When a channel is closed, it will no longer be readable and typing to it will result in a panic.

Here's an example:

main.go
ch := make(chan int)
close(ch)

// checking if a channel is closed using a select statement
select {
case <-ch:
    // channel can still be read
    fmt.Println("channel is open")
default:
    // channel is closed
    fmt.Println("channel is closed")
}
253 chars
13 lines

In this example, we create a channel ch and close it using close(ch). We then use a select statement to check if the channel is closed. Since the channel is closed, trying to read from it using <-ch would result in a deadlock. Instead, the default case is executed, indicating that the channel is closed.

related categories

gistlibby LogSnag