乐闻世界logo
搜索文章和话题

How do you close a channel in Go?

1个答案

1

In Go, closing a channel is a crucial operation primarily used to notify the receiving goroutine that all data has been sent. To close a channel, you can use the built-in close function. However, it's important to note that only the sender can close the channel; the receiver cannot do so, or it will cause a runtime panic. Additionally, closing the same channel multiple times will also result in a panic.

Here is a simple example demonstrating how to close a channel:

go
package main import ( "fmt" "sync" ) func main() { ch := make(chan int) // Create an int-type channel // Start a goroutine to send data go func() { for i := 0; i < 5; i++ { ch <- i // Send data to the channel } close(ch) // Close the channel after sending }() // In the main goroutine, receive data for num := range ch { fmt.Println(num) } fmt.Println("Channel closed and all data received.") }

In this example, we create a channel named ch of type int and send five numbers to it within a goroutine. After sending these numbers, we use close(ch) to close the channel. In the main goroutine, we use a for loop with range to receive data from the channel, which continues until the channel is closed.

After closing the channel, any attempt to send data to it will cause a panic, so it's crucial to close the channel only after all data has been sent. Additionally, using a range loop to receive data automatically handles the channel closure and terminates the loop.

2024年8月7日 17:39 回复

你的答案