Middle
What can be done with a closed channel in Go?
sobes.tech AI
Answer from AI
When reading from a closed channel, you can get all remaining data that was written before the closure. Once the channel is drained, subsequent read operations will return the zero value of the channel's element type and false as the second return value, indicating that the channel is closed.
Sending data to a closed channel will cause a runtime panic.
Attempting to close an already closed channel will also cause a runtime panic.
You can check if a channel is closed by using the ok operator during a read:
package main
import (
"fmt"
)
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
close(ch)
// Reading from a closed channel until drained
val1, ok1 := <-ch
fmt.Printf("Value: %d, Ok: %t\n", val1, ok1) // Value: 1, Ok: true
val2, ok2 := <-ch
fmt.Printf("Value: %d, Ok: %t\n", val2, ok2) // Value: 2, Ok: true
// Reading after the channel is drained
val3, ok3 := <-ch
fmt.Printf("Value: %d, Ok: %t\n", val3, ok3) // Value: 0, Ok: false
// Attempting to send to a closed channel (will cause panic)
// ch <- 3 // Uncommenting this line will cause a panic
// Attempting to close an already closed channel (will cause panic)
// close(ch) // Uncommenting this line will cause a panic
}
Using range with a closed channel allows reading data sequentially until the channel is drained, after which the loop automatically ends.
package main
import (
"fmt"
)
func main() {
ch := make(chan int, 3)
ch <- 10
ch <- 20
close(ch)
// Using range with a closed channel
for val := range ch {
fmt.Println(val) // Will print 10, then 20
}
}