File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -4717,6 +4717,42 @@ m := <-ch or {
47174717y := <-ch2 ?
47184718```
47194719
4720+ Note: buffered channels can be closed while they have unread values in them.
4721+ The buffered values can be retrieved, even after the closing:
4722+ ``` v
4723+ ich := chan int{cap: 5}
4724+ for i in 0 .. 5 {
4725+ ich <- i
4726+ }
4727+
4728+ for _ in 0 .. 2 {
4729+ x := <-ich or { break }
4730+ eprintln('>> loop 0..2 | x: ${x} | ich.closed: ${ich.closed}')
4731+ }
4732+
4733+ ich.close()
4734+
4735+ for {
4736+ x := <-ich or { break }
4737+ eprintln('>> final loop | x: ${x} | ich.closed: ${ich.closed}')
4738+ }
4739+ ```
4740+ ... will produce:
4741+ ```
4742+ >> loop 0..2 | x: 0 | ich.closed: false
4743+ >> loop 0..2 | x: 1 | ich.closed: false
4744+ >> final loop | x: 2 | ich.closed: true
4745+ >> final loop | x: 3 | ich.closed: true
4746+ >> final loop | x: 4 | ich.closed: true
4747+ ```
4748+
4749+ Note: reading from the .closed field of the channel in the example,
4750+ is done just for clarity of illustration. The recommended way to pop values
4751+ from the channel is with: ` x := <-ich or { break } ` in a ` for ` loop,
4752+ which will cleanly break out of the loop, when the channel is closed and empty.
4753+ Avoid manually checking, whether the channel was closed or not, because that
4754+ can introduce data races, if you are not careful.
4755+
47204756#### Channel Select
47214757
47224758The ` select ` command allows monitoring several channels at the same time
You can’t perform that action at this time.
0 commit comments