Go course

ChannelsClose, Range, and Channel Direction

Go

Display

Theme

Channels · Test exercise

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:

TypeMeaning
chan Tcan send and receive
chan<- Tsend-only (the arrow points into chan)
<-chan Treceive-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.

  1. produksi(pesan []string, out chan<- string) sends each message to out in order, formatted as "[baru] " + pesan (baru means "new"), and then closes out.
  2. kumpulkan(in <-chan string) []string uses range to receive every value until the channel is closed, then returns them as a slice (return an empty slice, not nil, if there are no messages).
main.go
package main

import "fmt"

func produksi(pesan []string, out chan<- string) {
	// TODO: kirim "[baru] " + pesan untuk setiap pesan, lalu tetap tutup out
	close(out)
}

func kumpulkan(in <-chan string) []string {
	// TODO: range sampai channel ditutup
	return nil
}

func notifikasi(pesan []string) []string {
	ch := make(chan string)
	go produksi(pesan, ch)
	return kumpulkan(ch)
}

func main() {
	hasil := notifikasi([]string{"Dina: halo!", "Eko: sudah sampai?", "Dina: on the way"})
	for _, n := range hasil {
		fmt.Println(n)
	}
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)