Home >Backend Development >Golang >When will golang defer be executed?

When will golang defer be executed?

(*-*)浩
(*-*)浩Original
2019-12-03 10:00:452618browse

When will golang defer be executed?

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
Output

package main

func main() {
    test()
}func test() {

    println("test1")
        panic("panic")    defer func() {
        println("defer test2")
    }()
    
    println("test3")
}
The delay function is not executed. Why is this? It’s because panic is before the delay function. Change the code as follows

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 delay function is executed and you can see panic The delayed function cannot be executed before the delayed function, after all, an exception will be thrown.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn