《字节》1.go channel close后读写的问题

结论:
1.无缓存的channel,关闭后,读取就是类型0值,写入就是panic

package main

import "fmt"

func main() {
    Test1()
}

func Test1() {
    ch := make(chan int,0)
    fmt.Println(len(ch),cap(ch))
    close(ch)
    for i := 0;i <5; i++ {
    fmt.Println(<-ch)
    }
    ch<-1
}
[Running] go run "c:\Users\Desktop\workspace\project1\zj-1\main.go"
0 0
0
0
0
0
0
panic: send on closed channel

2.有缓存的channel关闭后,读取就把缓存里的数据读出来,读完就是类型0值得,写入
都是panic

func Test2(){
    ch:=make(chan int,1)
    ch<-1
    close(ch)
    for i:=0;i<5;i++{
        v,ok:=<-ch
        if ok{
            fmt.Println("读取出来,value=",v)
        }else{
   fmt.Println("channel关闭了值为",v)
        }
    }

    ch<-1
    
}
[Running] go run "c:\Users\Desktop\workspace\project1\zj-1\main.go"
读取出来,value= 1
channel关闭了值为 0
channel关闭了值为 0
channel关闭了值为 0
channel关闭了值为 0
panic: send on closed channel

你可能感兴趣的:(go面试)