调用log.Fatalln时是否调用延迟函数? [英] Are deferred functions called when calling log.Fatalln?
问题描述
db, err := sql.Open("postgres", "…")
if err != nil {
log.Fatalln(err)
}
defer db.Close()
tpl, err := template.ParseGlob("")
if err != nil {
log.Fatalln(err)
}
如果 template.ParseGlob( )
返回一个错误,是 db.Close()
仍然被调用?
If template.ParseGlob("")
returns an error, is db.Close()
still being called?
推荐答案
不,延迟函数不会运行。
No, the deferred functions aren't run.
下面是 log.Fatal :
致命等同于Print(),后跟调用os.Exit(1)。
Fatal is equivalent to Print() followed by a call to os.Exit(1).
log.Fatal
调用 os.Exit
,其描述为此处:
退出导致当前程序以给定的状态码退出。
通常情况下,代码零表示成功,错误不为零。
程序立即终止;延期功能不运行。
Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.
如果您确实需要在程序结束前正确关闭资源或完成某些任务,请不要使用 log.Fatal
。
If you really need to properly close resources or do some tasks before the program finishes, then don't use log.Fatal
.
这篇关于调用log.Fatalln时是否调用延迟函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!