Close, Range, and Channel Direction
Closing a channel
A sender can announce that no more values will be sent with close:
close(ch)
Once a channel is closed:
- receivers can still take whatever values are left in the buffer,
- once it's empty, a receive returns the zero value immediately, without blocking,
- sending to a closed channel causes a panic, and so does closing it twice.
A receiver can check whether the channel has been closed with comma-ok, just like with a map:
v, ok := <-ch // ok == false jika channel sudah ditutup DAN kosong
Rule of thumb: the sender closes the channel, not the receiver. You also don't have to close every channel; close it only when the receiver needs to know the data has run out.
range over a channel
A for ... range loop over a channel receives values one at a time until the channel is closed:
for pesan := range ch {
fmt.Println(pesan)
}
// loop berakhir setelah close(ch) dan semua nilai diterima
If the sender forgets to close the channel, this loop waits forever.
Channel direction
You can restrict a channel type to one direction, usually in function parameters:
| Type | Meaning |
|---|---|
chan T | can send and receive |
chan<- T | send-only (the arrow points into chan) |
<-chan T | receive-only (the arrow points out of chan) |
func produsen(out chan<- int) {
out <- 1
close(out)
// v := <-out // error kompilasi: tidak bisa menerima dari channel kirim-saja
}
func konsumen(in <-chan int) {
for v := range in {
fmt.Println(v)
}
// in <- 2 // error kompilasi: tidak bisa mengirim ke channel terima-saja
}
A plain chan T can be passed to a chan<- T or a <-chan T parameter automatically. By restricting direction, you let the compiler make sure each function sticks to its role, and the code becomes easier to read.
Task
A chat app sends notifications through a producer–consumer pipeline. The notifikasi function is already there and connects the two.
produksi(pesan []string, out chan<- string)sends each message tooutin order, formatted as"[baru] " + pesan(barumeans "new"), and then closesout.kumpulkan(in <-chan string) []stringusesrangeto receive every value until the channel is closed, then returns them as a slice (return an empty slice, notnil, if there are no messages).