Golang range channel、close channel 遍历和关闭

Golang channel的range、close操作

关于channel读取时的返回值

Often, functions use these additional results to indicate some kind of error, either by returning an error as in the call to os.Open, or a bool, usually called ok. If a map lookup, type assertion, or channel receive appears in an assignment in which two results are expected, each produces an additional boolean result:
v, ok = m[key] // map lookup
v, ok = x.(T) // type assertion
v, ok = <-ch // channel receive

对上的文字解释下:map查找,类型断言和读channel数据都会返回两个值,第二个返回值是表示成功或失败的布尔值。
读channel时,第二个值返回为false时表示channel被关闭。

一、循环从channel中读取数据

  1. 方法一:
for{
    if value,ok:=<-ch;ok{
        //do somthing
    }else{
        break;//表示channel已经被关闭,退出循环
    }
}
  1. 方法二:
//range
ch:=make(chan int ,3)
ch<-1
ch<-2
ch<-3

for value:=range ch{
    fmt.Print(value)
}

//输出:123
//然后会一直阻塞当前协程,如果在其他协程中调用了close(ch),那么就会跳出for range循环。这也就是for range的特别之处

二、关闭channel

关闭一个channel只需要调用函数close()即可

注意:
1. 如果channel已经关闭,继续往它发送数据会导致panic: send on closed channel
2. 关闭一个已经关闭的channel也会导致panic: close of closed channel
3. channel关闭后,仍然可以从中读取以发送的数据,读取完数据后,将读取到零值,可以多次读取。

func test(){
    ch:=make(chan int,3)
    ch<-3
    ch<-2
    ch<-1
    close(ch)
    fmt.Print(<-ch)
    fmt.Print(<-ch)
    fmt.Print(<-ch)
    fmt.Print(<-ch)
    fmt.Print(<-ch)
}

//输出:32100
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值