After the golang channel is closed, the remaining data can be continued to be read.
Please see the test example below.
Create a channel with buffer, send data to the channel, then close the channel, and finally, read the data from the channel, output the result.
package main import ( "fmt" ) func main(){ ch := make(chan int, 3) ch <-1 ch <-2 ch <-3 close(ch) for value := range ch { ("value:", value) } }
output:
value: 1
value: 2
value: 3
It can be seen that after the channel is closed, the remaining data can still be read from the channel until all the data is read.
To put it more, for a closed channel, if you continue to send data to the channel, it will cause panic.
If you continue reading the data, you get a zero value (for int, it is 0).
There are two ways to judge a channel:
One way:
value, ok := <- ch
If ok is false, it means it has been closed.
Another way is the method used in the above example:
for value := range ch { }
If the channel is closed, the loop will be jumped.
In addition, if the channel is closed and cannot be written again, writing will cause panic. But it can be read all the time, and the value read is a zero value of type:
for i:=0;i<10;i++ { value := <- ch ("value:", value) }
value: 1
value: 2
value: 3
value: 0
value: 0
value: 0
value: 0
value: 0
value: 0
value: 0
This is the introduction to this article about whether the remaining data can be read after Golang channel is closed. For more information about Golang channel closing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!