go lang range chan
时间: 2023-06-30 17:16:34 浏览: 57
In Go language, the `range` keyword is often used to iterate over the elements of an array, slice, map, or channel. When used with a channel, the `range` statement iterates over the values sent on the channel until the channel is closed.
Here's an example of using the `range` keyword to receive values from a channel:
```
ch := make(chan int)
go func() {
for i := 0; i < 5; i++ {
ch <- i
}
close(ch)
}()
for v := range ch {
fmt.Println(v)
}
```
In this example, a new goroutine is launched to send values to the channel `ch`. After sending 5 values, the channel is closed using the `close` function. Then, in the main goroutine, the `range` statement is used to receive values from the channel until it is closed. Each value received is printed to the console.
Note that the `range` statement will block until a value is received from the channel. Once a value is received, the loop body is executed with the received value. When the channel is closed, the loop will terminate.
Also note that if the channel is not closed, the `range` statement will block indefinitely, waiting for values to be sent on the channel. So it's important to make sure that channels are closed when you're done sending values on them.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)