go defer简单理解

来源:互联网 发布:共享 网络打印机 运行 编辑:程序博客网 时间:2024/06/05 11:19

今天看collider 代码的时候发现了,如何语句:
// room returns the room specified by |id|, or creates the room if it does not exist.
func (rt *roomTable) room(id string) *room {
rt.lock.Lock()
defer rt.lock.Unlock()

return rt.roomLocked(id)

}

这个defer 是什么,网上找了段不错的说明:
即延迟(defer)语句,你可以在函数中添加多个defer语句。当函数执行到最后时,这些defer语句会按照逆序执行,最后该函数返回。特别是当你在进行一些打开资源的操作时,遇到错误需要提前返回,在返回前你需要关闭相应的资源,不然很容易造成资源泄露等问题。

很明显我上面的代码就是函数最后执行rt.lock.Unlock()
操作

这文章对defer讲的很不错:blog.csdn.net/eclipser1987/article/details/12089271

原创粉丝点击