【GO】go语言channel的关闭管道的遍历

1. channel的关闭

使用内置函数close可以关闭channel,当channel关闭后,就不能再向channel写数据了,但是仍然可以从该channel读取数据

案例演示:

package main
import (
    "fmt"
)
 
func main() {
    intChan := make(chan int, 3)
    intChan <- 100
    intChan <- 200
    close(intChan) // close
    // 这时不能够再向channel写入
    // intChan <- 300
    fmt.Println("okok")
    // 当管道关闭后,读取数据是可以的
    n1 := <- intChan
    fmt.Println(n1)
}
2. 管道的遍历

channel 支持 for-range的方式进行遍历,请注意两个细节

1)在遍历时,如果channel没有关闭,则会出现deadlock 的错误

2)在遍历时,如果channel已经关闭,则会正常遍历数据,遍历完后,就会退出遍历

3)不使用for进行遍历,假如使用for进行遍历长度为100的channel数据,最后拿出来的只有50条

3. channel遍历和关闭的案例演示

看代码演示:

package main
import (
    "fmt"
)
 
func main() {
    intChan := make(chan int, 100)
    for i := 0; i < 100; i++ {
        intChan <- i * 2 // 放入100个数据到管道
    }
 
    // 遍历管道时,不能使用普通的for循环结构
    // for i := 0; i < len(intChan); i++ {
    // }
    
    // 如果在遍历时没有关闭channel,则会出现deadlock错误
    // close(intChan)
    // for v := range intChan {
    //     fmt.Println("v=",v)
    // }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值