Home >Backend Development >Golang >Is Receive or Send Evaluated First in a Go `select` Statement?

Is Receive or Send Evaluated First in a Go `select` Statement?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 00:48:02670browse

Is Receive or Send Evaluated First in a Go `select` Statement?

Unveiling the Dynamics of Receive and Send Operations in select Statements

When seeking to forward channel results, many opt for the following construct:

for {
    select {
        ...
        case ch2 <- (<-ch1):
        ...
    }
}

Examining this code raises the question: what aspect of the select operation is being evaluated, the receiving or sending action?

The Go documentation sheds light on this:

The channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement.

This implies that in the given example, the expression <-ch1 is assessed immediately, and the select statement proceeds to determine whether the send to ch2 or an alternative case will be executed.

Effectively, this method enables immediate blocking on the receive from ch1, with the select ultimately controlling the subsequent send on ch2. However, it's worth noting that even if an alternate case is chosen, the value from ch1 would still be consumed and discarded.

The above is the detailed content of Is Receive or Send Evaluated First in a Go `select` Statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn