Channels can be closed. If a channel is closed, no values can be
sent on it. A channel is open the moment you create it,
e.g. c := make(chan int, 5)
.
You may want to close a channel, to indicate completion. That is to say, when the goroutines are completed it may be the channel has no reason to be open.
Example
Closing channel
The line c := make(chan int, 5)
creates a buffered
channel of capacity 5. A buffered channel can store multiple values
without it being received.
Then data is sent to the channels with the lines
c <- 5
and c <- 3
.
The channel is closed with the function
close(channel)
.
package main
func main() {
:= make(chan int, 5)
c <- 5
c <- 3
c close(c)
}
If you sent data after the channel is closed, like
c <- 1
after the close(c)
call, it will
throw this error:
$ go run example.go
panic: send on closed channel
goroutine 1 [running]:
main.main()
/home/linux/golang/example.go:11 +0x9b
exit status 2
Receive data
If a channel is closed, you can still read data. But you cannot send
new data into it. This program reads both before and after closing the
channel, which works. It’s closed only for sneding, meaning a
line like c <- 9
won’t work after
close(c)
.
package main
import "fmt"
func main() {
:= make(chan int, 5)
c
<- 5
c <- 3
c
.Println(<-c)
fmtclose(c)
.Println(<-c)
fmt}