golang中的close函数

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)

欢迎补充指正!

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值