diff --git a/examples/closing-channels/closing-channels.go b/examples/closing-channels/closing-channels.go index 926d9b5..b00fff7 100644 --- a/examples/closing-channels/closing-channels.go +++ b/examples/closing-channels/closing-channels.go @@ -47,4 +47,10 @@ func main() { // [synchronization](channel-synchronization) approach // we saw earlier. <-done + + // It is possible to read from an empty closed channel, + // but instead of waiting for a message, we will + // immediately receive a zero value of the channel's type. + j := <-jobs + fmt.Println("no jobs to receive", j) } diff --git a/examples/closing-channels/closing-channels.hash b/examples/closing-channels/closing-channels.hash index 3e33a07..1079571 100644 --- a/examples/closing-channels/closing-channels.hash +++ b/examples/closing-channels/closing-channels.hash @@ -1,2 +1,2 @@ -8f26c901e0f14df2ca40329a354c3ac86a5c3a07 -vCvRjcMq7p3 +56d8d399e304cdf5ab36663b43397ca43126e260 +cNvXGNi9l27 diff --git a/examples/closing-channels/closing-channels.sh b/examples/closing-channels/closing-channels.sh index 013f8a8..99cb663 100644 --- a/examples/closing-channels/closing-channels.sh +++ b/examples/closing-channels/closing-channels.sh @@ -7,6 +7,11 @@ sent job 3 received job 3 sent all jobs received all jobs +no jobs to receive 0 -# The idea of closed channels leads naturally to our next -# example: `range` over channels. +# Be sure that channel is not closed when you read +# from it, especially when iterating over a channel. +# Otherwise you might get an unexpected result or +# even enter an infinite loop. +# To learn how to correctly use `range` over channels, +# see our next example. diff --git a/public/closing-channels b/public/closing-channels index a631097..186dcb3 100644 --- a/public/closing-channels +++ b/public/closing-channels @@ -43,7 +43,7 @@ completion to the channel’s receivers.
package main
<-done
+ It is possible to read from an empty closed channel, +but instead of waiting for a message, you will +immediately return zero value of the channel’s type.
+ <-done
+ j := <-jobs
+ fmt.Println("no jobs to receive", j)
}
The idea of closed channels leads naturally to our next
-example: range
over channels.
Be sure that channel is not closed when you read
+from it, especially when iterating over a channel.
+Otherwise you might get an incorrect result or
+even enter an infinite loop.
+To learn how to correctly use range
over channels,
+see our next example.
range
over channels.