CodeBlanks Logo Icon CodeBlanks

Closing a channel

Learn to close a channel with close and detect closure.

Closing a channel

You close a channel with close(ch). Sending on a closed channel panics; receiving from a closed channel returns the zero value. This is how you signal that no more data will come.

With v, ok := <-ch you learn if the channel is open. If ok is false the channel is closed and drained. The for v := range ch loop ends automatically when the channel closes.

close and range

Closing a channel pairs with for v := range ch. The sender calls close(ch) after all data is sent; the receiver's range loop ends automatically.

The sender, not the receiver, should close the channel; if the receiver closes it the sender may panic. Following this principle is key for safe concurrency.

Practice Close a channel and print

Inside main, add a make(chan string) call and print closed with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    ch := make(chan string, 1)
    ch <- "kapatıldı"
    close(ch)
    fmt.Println(<-ch)
}

Expected output

kapatıldı

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens when you send on a closed channel?

  • Silently ignored
  • It panics Correct answer
  • It blocks
  • Returns zero value

Explanation: it panics. RECEIVING from a closed channel returns zero value.

2 Closing a channel

Question
ch := make(chan int, 2)
ch <- 1
ch <- 2
____
for v := range ch {
    fmt.Println(v)
}
Answer
ch := make(chan int, 2)
ch <- 1
ch <- 2
close(ch)
for v := range ch {
    fmt.Println(v)
}

Explanation: In Go close is a function, not a method.

3 Match close concepts

Term Meaning
close(ch) Close
v, ok Status
range Auto-end
panic Send on closed

All lessons in Intermediate