Is there any way to check if values are buffered in a Go chan?

Issue

How can I do something like the following?:

func foo(input <-chan char, output chan<- string) {
    var c char
    var ok bool
    for {
        if ThereAreValuesBufferedIn(input) {
            c, ok = <-input
        } else {
            output <- "update message"
            c, ok = <-input
        }
        DoSomethingWith(c, ok) 
    }
}

Basically, I want to check if there are buffered values in the chan so that if there aren’t, I could send an update message before the thread is blocked.

Solution

package main

func foo(input <-chan char, output chan<- string) {
        for {
                select {
                case c, ok := <-input:
                        if ok { // ThereAreValuesBufferedIn(input)
                                ... process c
                        } else { // input is closed
                                ... handle closed input
                        }
                default:
                        output <- "update message"
                        c, ok := <-input // will block
                        DoSomethingWith(c, ok)
                }

        }
}

EDIT: Fixed scoping bug.

Answered By – zzzz

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.