只读通道,是无需关闭的吗?调用 close 函数会报错

各位大佬们,想问个问题,只读通道是无法通过 close 函数关闭的吗?还是说无需关闭?

c := make(<-chan int)
close(c)

c2 := make(chan<- int)
close(c2)

上面图里,在 goland 里,close(c) 会报错,close(c2) 没有问题,关键是知道错误原因,也不知道怎么改

只读通道,是无需关闭的吗?调用 close 函数会报错

讨论数量: 1

答:不能通过 close() 函数关闭只读 channel

如果执行编译的话会发现编译提示 invalid operation: cannot close receive-only channel c (variable of type <-chan int)

Go 的源码 builtin.go 中 close 函数有这样的一串注释。

// The close built-in function closes a channel, which must be either
// bidirectional or send-only. It should be executed only by the sender,
// never the receiver, and has the effect of shutting down the channel after
// the last sent value is received. After the last value has been received
// from a closed channel c, any receive from c will succeed without
// blocking, returning the zero value for the channel element. The form
//
//    x, ok := <-c
//
// will also set ok to false for a closed and empty channel.
func close(c chan<- Type)
1周前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!