golang之关闭channel

channel在已关闭的情况下

向channel中发送数据会引发:"panic: send on closed channel"

如果channel通道中还有数据、则可以读取其中的数据

如果channel通道中没有数据、则根据channel定义的数据类型不同、返回值不同、int返回0、string返回空字符串、指针返回地址、bool返回false。总的来说、返回空,不会引发panic

实例

package main

import (
    "fmt"
    "time"
)

func main() {
    //定义一个缓冲channel 长度为2
    ch1 := make(chan *string, 2)
    s := "test"
    go func() {
        ch1 <- &s
        ch1 <- &s
        close(ch1)
    }()
    for {
        select {
        case v1 := <-ch1:
            fmt.Printf("v1 : %v\n", v1)
            time.Sleep(2*time.Second)
            //输出结果为:
            //v1 : 0xc42000e1e0
            //v1 : 0xc42000e1e0
            //v1 : <nil>
            //v1 : <nil>
            //v1 : <nil>
            // ...
        }
    }
}

 可以通过 okdom模式判断channel是否关闭、如下:

i, ok := <- ch1
if ok {
  fmt.Printf("i : %v\n", i)
} else {
  fmt.Printf("channel closed\n")
}

 

posted on 2018-02-02 11:04  残天  阅读(1095)  评论(0)    收藏  举报

导航