Golang has a special control statement, which is defer. The defer statement is used to delay calling the specified function, such as releasing resources, etc. It will be executed at the end of the function, but Before Return, , let's take a brief understanding of the code: (Recommended learning: Go )
package main func main() { test() }func test() { println("test1") defer func() { println("defer test2") }() println("test3") }
## The execution results are as follows: ## 在##It is clear that the function with defer is executed last
Now change the code to make the code panic. When an exception is thrown, will the defer delay function still be executed?
test1 test3 defer test2
package main func main() { test() }func test() { println("test1") panic("panic") defer func() { println("defer test2") }() println("test3") }
test1
panic: panic
Process finished with exit code 2
Output
package main func main() { test() }func test() { println("test1") defer func() { println("defer test2") }() panic("panic") println("test3") }
The above is the detailed content of When will golang defer be executed?. For more information, please follow other related articles on the PHP Chinese website!