Home > Article > Backend Development > Is golang chan closed?
chan is a very important thing in golang, used for goroutine communication, because the golang program will inevitably have multiple goroutines, how to synchronize these goroutines is Very important.
When using chan, there are a few experiences: (Recommended learning: Go )
First of all, it will always be a symbol & lt Reading or writing, such as v,ok := <-c is reading, and c <- v is writing.
Secondly, when reading, if there is no ok, it can also be read. However, if it is closed, it can be read, and there is no assignment; if you want to know whether it is closed, you need to add ok, that is, unless chan is never closed, reading should use v,ok := <-c instead of v := < ;-c way.
Again, you cannot write to the closed chan, so generally when writing, you need to use a signal chan (generally the buffer is 1) to determine whether to write or give up. Use select to determine whether the write is successful. , or it is closing and needs to give up writing.
Finally, if chan has data after closed, ok will still be true, and it will be false until chan has no data.
When a chanel is closed, retrieval will not block, but will return zero value
package main import "fmt" func main() { c := make(chan int, 5) c <- 123 close(c) fmt.Println(<-c) fmt.Println(<-c) }
Output
123 0
The above is the detailed content of Is golang chan closed?. For more information, please follow other related articles on the PHP Chinese website!