Wählt „Wählen' „Empfangen' oder „Senden' im Fall von ch2 aus

Barbara Streisand
Freigeben: 2024-11-15 07:58:02
Original
743 Leute haben es durchsucht

Does `select` Choose to Receive or Send in `case ch2

Receiving and Sending Within a Single Case Statement

In Go, it's possible to combine receive and send operations within the same select case statement, as demonstrated by this code snippet:

for {
    select {
    ...
    case ch2 <- (<-ch1):
    ...
    }
}
Nach dem Login kopieren

This code aims to forward the results of channel ch1 to channel ch2. However, it raises the question of which operation, receiving from ch1 or sending to ch2, the select statement selects on.

The Selection Process

As explained in the Go documentation, when entering a select statement:

  • Channel expressions in receive operations and send statements are evaluated, yielding a set of channels to receive from or send to, along with corresponding values for sending.
  • Any side effects occur immediately during this evaluation.
  • Expressions on the left-hand side of a receive operation with a short variable declaration or assignment are not evaluated.

Implications for the Given Code

In the provided example, the following occurs:

case ch2 <- (<-ch1):
Nach dem Login kopieren
  • The expression <-ch1 is evaluated, blocking immediately on the receive from ch1.
  • The resulting value is stored in the temporary variable on the left-hand side of the assignment.
  • The select statement then controls whether the send operation on ch2 occurs.

Therefore, the select statement selects on whether to send the received value from ch1 to ch2 or handle a different case.

Side Effect

It's important to note that even if the receive operation from ch1 is not ultimately selected, the value is still consumed and discarded. This behavior can be significant and should be considered when using this pattern.

Das obige ist der detaillierte Inhalt vonWählt „Wählen' „Empfangen' oder „Senden' im Fall von ch2 aus. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage