Go实战--golang中defer的使用(有事没事defer一下)
生命不止,继续 go go go !!!
学习golang这么久了,还没看到类似传统的 try…catch…finally 这种异常捕捉方式。
但是,Go中引入的Exception处理:defer, panic, recover。
那么今天跟大家分享一下golang中的defer。闲言少叙,看一下defer的作用:
Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages.
defer的思想类似于C++中的析构函数,不过Go语言中“析构”的不是对象,而是函数,defer就是用来添加函数结束时执行的语句。注意这里强调的是添加,而不是指定,因为不同于C++中的析构函数是静态的,Go中的defer是动态的。
引自:http://www.cnblogs.com/ghj1976/archive/2013/02/11/2910114.html
说多无用,想来个开胃菜,看看如何使用:
package main
import <
还没有评论,来说两句吧...