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

你可能感兴趣的:(Go)