Junior — Middle
How can you close a channel in the program?
sobes.tech AI
Answer from AI
In Go, the close() function is used to finish working with a channel. Closing a channel signals to receivers that no more values will be sent. After closing a channel, attempting to send to it will cause a panic, but reading from a closed channel is possible — it will return the zero value and false as the second return value.
Example:
ch := make(chan int)
go func() {
ch <- 42
close(ch) // Close the channel after sending
}()
for val := range ch {
fmt.Println(val) // Will print 42
}
Thus, to finish working with a channel, you need to call close(channel).