Checking if a channel has a ready-to-read value, using Go

The only non-blocking operation I know of to read from a channel is inside a select block having a default case :

    select {
    case x, ok := <-ch:
        if ok {
            fmt.Printf("Value %d was read.\n", x)
        } else {
            fmt.Println("Channel closed!")
        }
    default:
        fmt.Println("No value ready, moving on.")
    }

Please try the non-blocking here

Note about previous answers: the receive operator itself is now a blocking operation, as of Go 1.0.3 . The spec has been modified. Please try the blocking here (deadlock)

Leave a Comment