defer statement
Original link: Functions based on Go language | Li Wenzhou’s blog
defer is to delay processing of subsequent statements.
Important: When defer registers a function to be delayed, all parameters of the function need to determine their values.
for example:
func Defer() {
defer fmt.Println(1)
defer fmt.Println(2)
fmt.Println(3)
defer fmt.Println(4)
}
//output
3
4
2
1
In the Go language function, return
the statement is not an atomic operation at the bottom. It is divided into two steps: assigning a return value and the RET instruction. The timing of statement execution is defer
after the return value assignment operation and before the RET instruction is executed. The details are shown in the figure below:
some built-in functions
panic/recover
panic is used to set error reporting. You can set panic to the place where we think an error will occur.
Example:
func Panic() {
fmt.Println("A")
panic("B")
fmt.Println("C")
}
//output
A
panic: B
goroutine 1 [running]:
study/neizhihanshu.Panic()
D:/Project/GoLang/go_study/neizhihanshu/nzhs.go:17 +0x65
main.main()
D:/Project/GoLang/go_study/main.go:87 +0x17
进程 已完成,退出代码为 2
We can restore the program through recovery.
func Recover() {
fmt.Println("A")
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
panic("B")
fmt.Println("C")
}
//output
A
B
进程 已完成,退出代码为 0
recover can only intercept errors before panic, but cannot prevent errors later.
func Recover() {
fmt.Println("A")
panic("B")
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
fmt.Println("C")
}
//output
A
panic: B
goroutine 1 [running]:
study/neizhihanshu.Recover()
D:/Project/GoLang/go_study/neizhihanshu/nzhs.go:27 +0x6a
main.main()
D:/Project/GoLang/go_study/main.go:87 +0x17
进程 已完成,退出代码为 2