In golang, we use the defer statement to perform some error handling and finishing work. Its function is similar to the finally keyword in Java. However, whether it is Java's finally keyword or C's Raii class, we can clearly know their scope and execution timing. So when is the content processed by the defer keyword in golang executed?
First of all, the official document says:defer will be executed when the function returns, the function ends, or the corresponding goroutine panics.
Then it should be noted that because golang supports multi-value returns, the return value is pushed onto the stack before returning, while the c language stores the return value in a register and returns it.
When golang returns, it first pushes the return value onto the stack; then executes the defer function. If the return value in the stack is modified in the defer function (but this should not be done), then the return value will be modified. ; Then jump back.
In this way we will know the timing of defer execution. Even if you write defer far before return, it will still be executed before the function returns.
If there are multiple defers in a scope, the execution order before returning is to execute the defer called later first, and then execute the defer called earlier.
There are several examples in the official documents that can well illustrate the timing of defer, as follows:
lock(l) defer unlock(l) // unlocking happens before surrounding function returns // prints 3 2 1 0 before surrounding function returns for i := 0; i <= 3; i++ { defer fmt.Print(i) } // f returns 1 func f() (result int) { defer func() { result++ }() return 0 }
Recommended related articles and tutorials:golang tutorial
The above is the detailed content of When does the defer keyword take effect in golang?. For more information, please follow other related articles on the PHP Chinese website!