check if a channel is empty in go

To check if a channel is empty in Go, you can use a combination of the len function and a select statement.

Here's an example code snippet:

main.go
package main

import "fmt"

func main() {
    ch := make(chan int)

    // Start a goroutine that sends a value to the channel after a short delay
    go func() {
        // simulate some work
        time.Sleep(1 * time.Second)
        ch <- 42
    }()

    // Check if the channel is empty using len and select
    select {
    case <-ch:
        fmt.Println("Channel is not empty")
    default:
        fmt.Println("Channel is empty")
    }
}
446 chars
23 lines

In this code snippet, we create a channel ch and start a goroutine that waits for a short delay before sending a value to the channel. Then, we use a select statement with a default clause to check if the channel is empty. If a value is available on the channel, the first case will be triggered and we print "Channel is not empty". If the channel is empty, the default clause will be triggered and we print "Channel is empty".

gistlibby LogSnag