chan一定要显示close才会释放吗

channel不需要通过close释放资源,只要没有goroutine持有channel,相关资源会自动释放。

close可以用来通知channel接收者不会再收到数据

所以即使channel中有数据也可以close而不会导致接收者收不到残留的数据

有些场景需要关闭通道,例如range遍历通道,如不关闭range遍历会出现死锁

 

转载自:

https://www.h5w3.com/182223.html

 

单向 channel 有什么用

事实上Golang中的单向channel只是一种声明,主要是为了防止channel被滥用。

使用普通的channel也能完成任务,但是使用单向channel后如果出现滥用,在编译期间会报错,这样可以有效的提示开发者。

When using channels as function parameters, you can specify if a channel is meant to only send or receive values.
This specificity increases the type-safety of the program.

Golang的示例说明里面也表明这个主要是为了提高程序的类型安全 作者:soolaugust 链接:https:
//www.zhihu.com/question/362547316/answer/948215755 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

看一个示例

    package main

    import "fmt"
    var c =make(chan int)
    var d =make(chan<- int)
    func main(){
        fmt.Println("hello,world!")
        fmt.Println(len(a))
        d = c         // 不能写成 c = d
        go p(d,1000)  // 虽然传给了d,但是channel按引用传递,值也传递给c了
        fmt.Println(<-c)
    }
    
    func p(ch chan<- int, i int){
        ch<-i
    }

转载自:https://blog.csdn.net/cumt_TTR/article/details/105218836

 

posted @ 2022-06-25 15:21  许伟强  阅读(264)  评论(0编辑  收藏  举报