Go语言入门-延迟调用-defer
定义
func functionName([parameterList]) ([returnTypes]) {
defer statement
...
body
...
}
语句defer想当前函数注册一个稍微执行的函数调用,它会在主调函数或者方法返回之前但是其返回值(当返回值存在)计算后执行。
- 存在多个defer语句采用后进先出LIFO(Last In First Out)的顺序执行
- 主要用于释放资源、解出锁定、以及错误处理等场景。
- 示例1
简单的展示defer函数调用
func main() {
defer fmt.Println("end")
fmt.Println("start")
}
/**
output:
start
end
*/
- 示例2
多个延迟出则按照FILO次序执行。
func main() {
defer fmt.Println("end")
defer fmt.Println("end end")
defer fmt.Println("end end end")
fmt.Println("start")
}
/**
output:
start
end end end
end end
end
*/
示例3
defer与闭包
func callClosure() func() int {
x := 10
return func()(y int) {
x++
fmt.Println(x)
return x
}
}
func main() {
//获取callClosure函数返回的闭包函数
f := callClosure()
defer f() //注册延迟调用f()-->f()带状态
fmt.Println("main: ", f()) //调用闭包函数,并打印返回值
//最后在执行延迟注册的函数
}
/**
output:
11
main: 11
12
*/