How to close a channel in Golang?


We can close a channel in Golang with the help of the close() function. Once a channel is closed, we can't send data to it, though we can still read data from it. A closed channel denotes a case where we want to show that the work has been done on this channel, and there's no need for it to be open.

We open the channel the moment we declare one using the make keyword.

ch := make(chan int)

Example 1

Let's consider a very simple example, in which we will create a buffered channel and then pass data to it and then close the channel.

Consider the code shown below.

package main

import "fmt"

func main() {
   ch := make(chan int, 3)

   ch <- 2
   ch <- 3

   close(ch)
   fmt.Println("Channel closed!")
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Channel closed!

Example 2

It should be noted that, if we try to send some value to the channel after it has been closed, then we will get a panic.

Consider the code shown below.

package main

import "fmt"

func main() {
   ch := make(chan int, 3)

   ch <- 2
   ch <- 3

   close(ch)

   ch <- 5
   fmt.Println("Channel closed!")
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

panic: send on closed channel

goroutine 1 [running]:
main.main()
/home/cg/root/2773125/main.go:13 +0xd4
exit status 2

Example 3

Even though we can't send data to a closed channel, we can still read data from a closed channel. Consider the code shown below.

package main

import "fmt"

func main() {
   ch := make(chan int, 3)

   ch <- 2
   ch <- 3

   close(ch)

   <-ch
   fmt.Println("Channel closed!")
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

Channel closed!

Updated on: 01-Nov-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements