close函数是用于关闭通道的。
官方解释(摘自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 channel.
翻译过来就是:
close函数是一个内建函数, 用来关闭channel,这个channel要么是双向的, 要么是只写的(chan<- Type)。
这个方法应该只由发送者调用, 而不是接收者。
当最后一个发送的值都被接收者从关闭的channel(下简称为c)中接收时,
接下来所有接收的值都会非阻塞直接成功,返回channel元素的零值。
如下的代码:
如果c已经关闭(c中所有值都被接收), x, ok := <- c, 读取ok将会得到false。
验证如下:
package main
import "fmt"
func main() {
ch := make(chan int, 5)
for i := 0; i < 5; i++ {
ch <- i
}
close(ch) // 关闭ch
for i := 0; i < 10; i++ {
e, ok := <-ch
fmt.Printf("%v, %v\n", e, ok)
if !ok {
break
}
}
}
输出:
0, true
1, true
2, true
3, true
4, true
0, false
在close之后, 还可以读取, 不过在读取完之后, 再检测ok, 就是false了。
注意事项
对于值为nil的channel或者对同一个channel重复close, 都会panic, 关闭只读channel会报编译错误。
代码示例如下:
关闭值为nil的通道
var c4 chan int
// 运行时错误:panic: close of nil channel
close(c4)
重复关闭同一个通道
c3 := make(chan int, 1)
close(c3)
// 运行时错误:
// panic: close of closed channel
close(c3)
关闭只读通道
c3 := make(<-chan int, 1)
// 编译错误:
// invalid operation: close(c3) (cannot close receive-only channel)
close(c3)
正确的用法
c1 := make(chan int, 1) // 双向通道 (bidirectional)
c2 := make(chan<- int, 1) // 只写的 (send-only)
close(c1)
close(c2)
---------------------
作者:butterfly5211314
来源:CSDN
原文:https://blog.csdn.net/butterfly5211314/article/details/81842519
版权声明:本文为博主原创文章,转载请附上博文链接!