Can I be certain that the default branch of a select will never be selected when case channels are always be writable / readable?

114 views
Skip to first unread message

ran...@gmail.com

unread,
Mar 22, 2018, 11:46:26 AM3/22/18
to golang-nuts
Please read the title, and here is an example:

testChannel := make(chan struct{}, 1)

for {
    select {
        case testChannel <- struct{}{}:
            fmt.Println("Test Channel writen")
            <-testChannel

        default:
            panic("Should never panic?")
    }
}

Can I assume that the code above will never panic?

Thank you!

Jan Mercl

unread,
Mar 22, 2018, 11:50:19 AM3/22/18
to ran...@gmail.com, golang-nuts
On Thu, Mar 22, 2018 at 4:46 PM <ran...@gmail.com> wrote:

> Can I assume that the code above will never panic?

Yes:
""""
If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.
""""

No: If any another goroutine reads from 'testChannel'

--

-j

ran...@gmail.com

unread,
Mar 22, 2018, 11:32:08 PM3/22/18
to golang-nuts
OK, that make sense, thank you.
Reply all
Reply to author
Forward
0 new messages