How to Close Channel in Go: Syntax and Examples
In Go, you close a channel using the built-in
close() function by passing the channel as an argument, like close(ch). Closing a channel signals that no more values will be sent on it, allowing receivers to detect this and stop waiting.Syntax
The syntax to close a channel in Go is simple. Use the close() function with the channel variable inside the parentheses.
close(ch): Closes the channelch.- Only the sender should close the channel.
- Receivers can still receive remaining values until the channel is empty.
go
close(ch)
Example
This example shows how to create a channel, send values, close it, and receive values until the channel is empty.
go
package main import "fmt" func main() { ch := make(chan int) go func() { for i := 1; i <= 3; i++ { ch <- i } close(ch) // Close the channel after sending }() for val := range ch { fmt.Println(val) } fmt.Println("Channel closed, no more values.") }
Output
1
2
3
Channel closed, no more values.
Common Pitfalls
Common mistakes when closing channels include:
- Closing a channel more than once causes a panic.
- Closing a channel from the receiver side instead of the sender.
- Sending on a closed channel causes a panic.
Always let the sender close the channel and never send after closing.
go
package main import "fmt" func main() { ch := make(chan int) // Wrong: closing channel twice causes panic close(ch) // close(ch) // Uncommenting this line will cause panic: close of closed channel // Wrong: sending on closed channel causes panic // ch <- 1 // Uncommenting this line will cause panic fmt.Println("Avoid these mistakes.") }
Output
Avoid these mistakes.
Quick Reference
Remember these key points when working with channels and closing them:
- Use
close(ch)to close a channel. - Only the sender should close the channel.
- Do not send on a closed channel.
- Receivers can detect closed channels using
for val := range chor by checking the second value from receive.
Key Takeaways
Use close(ch) to close a channel when no more values will be sent.
Only the sender should close the channel to avoid panics.
Do not send values on a closed channel; it causes a runtime panic.
Receivers can detect closed channels by ranging over them or checking the second boolean value.
Closing a channel signals receivers that no more data is coming.