延迟函数defer
我们知道在Golang中有一个关键字defer
,用它来声明在函数调用前,会让函数*延迟**到外部函数退出时再执行,注意,这里的退出含义:函数return返回或者函数panic退出
defer的特性
defer
函数会在外层函数执行结束后执行
package main
import "fmt"
func main() {
defer fmt.Println(2)
fmt.Println(1)
}
/* output:
1
2
*/
defer
函数会在外层函数异常退出时执行
package main
import "fmt"
func main() {
defer fmt.Println(2)
panic(1)
}
/* output:
2
panic: 1
goroutine 1 [running]:
main.main()
/tmp/sandbox740231192/prog.go:7 +0x95
*/
3.如果函数中有多个defer
函数,它们的执行顺序是LIFO:
package main
import "fmt"
func main() {
defer fmt.Println(2)
defer fmt.Println(3)
fmt.Println(1)
}
/*output:
1
3
2
*/
defer的用途
释放资源
比如打开文件后关闭文件:
package main
import "os"
func main() {
file, err := os.Open("1.txt")
if err != nil {
return
}
// 关闭文件
defer file.Close()
// Do something...
}
又比如数据库操作操作后取消连接
func createPost(db *gorm.DB) error {
conn := db.Conn()
defer db.Close()
err := conn.Create(&Post{Author: "Draveness"}).Error
return err
}
recover恢复
package main
import "fmt"
func main() {
defer func() {
if ok := recover(); ok != nil {
fmt.Println("recover")
}
}()
panic("error")
}
/*output:
recover
*/
总结
defer
函数总会被执行,无论外层函数是正常退出还是异常panic- 如果函数中有多个
defer
函数,它们的执行顺序是LIFO
在Python中的写一个defer
看到defer
这么好用,Pythoneer也可以拥有吗?当然
家里(Python)的条件
Python中有一个库叫做contextlib
,它有一个类叫ExitStack
,来看一下官网的介绍:
A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.
Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state.
Since registered callbacks are invoked in the reverse order of registration 这句是关键,他说注册的回调函数是以注册顺序相反的顺序被调用,这不就是defer
函数的第二个特性LIFO吗?
再看下ExitStack
类:
class ExitStack