Go OR-Done-Channel Pattern: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 11: Line 11:
</syntaxhighlight>
</syntaxhighlight>
The <code>for</code>/<code>range</code> syntax is simple and intuitive, but it cannot be used anymore if we want to [[Go_Channels#Use_a_done_Channel|make the loop preemptable by using a <code>done</code> channel]]. In that case we need to replace it with a <code>for</code>/<code>select</code> syntax and <code>case</code> for the state of the <code>done</code> channel (see an example [[Go_Channels#EB90|here]]).
The <code>for</code>/<code>range</code> syntax is simple and intuitive, but it cannot be used anymore if we want to [[Go_Channels#Use_a_done_Channel|make the loop preemptable by using a <code>done</code> channel]]. In that case we need to replace it with a <code>for</code>/<code>select</code> syntax and <code>case</code> for the state of the <code>done</code> channel (see an example [[Go_Channels#EB90|here]]).
The equivalent syntax is:
<syntaxhighlight lang='go'>
for v := range orDone(done, c) {
  // do something with the channel value, we exit the loop automatically when the 'c' channel is closed
  // or when the 'done' channel is messaged (written onto or closed)
  ...
}
</syntaxhighlight>
=<tt>orDone(...)</tt>=
The <code>orDone(...)</code> function:
<syntaxhighlight lang='go'>
</syntaxhighlight>

Revision as of 22:24, 5 February 2024

Internal

Overview

Reading from a channel until the channel is closed can be done by ranging over a channel:

for v := range c {
  // do something with the channel value, we exit the loop automatically when the channel is closed
  ...
}

The for/range syntax is simple and intuitive, but it cannot be used anymore if we want to make the loop preemptable by using a done channel. In that case we need to replace it with a for/select syntax and case for the state of the done channel (see an example here).

The equivalent syntax is:

for v := range orDone(done, c) {
  // do something with the channel value, we exit the loop automatically when the 'c' channel is closed
  // or when the 'done' channel is messaged (written onto or closed)
  ...
}

orDone(...)

The orDone(...) function: