Golang provides the defer
keyword to perform cleanup before a function exits. We won’t go into the basics of how to use it. Here’s a summary of some things to keep in mind.
defer execution order
Running results
That is, the order of execution of defer is the reverse of the order of code, which is last-in-first-out.
defer and return order of execution
|
|
Running results
You can see that the return statement is executed first and the defer function is executed later.
defer affects the return value
Since the function executed by defer is executed after the return statement. Can defer change the return value of a function? Consider the following example.
The result is 1024. return is 2048, i.e. defer can indeed change the return value of a function. Look at a similar example.
The result is 1024, where the defer func updates the result value but has no effect on the return value of the function. The reason for this is that the function’s return value of type int is unnamed (i.e. anonymous), so defer func cannot modify that return value, only the result variable.
defer function pre-calculates argument values
This example calculates the execution time of a function, sleep 1s as a simulation, and then the execution result is: 199ns, which is obviously not the expected result. The expected execution time should be greater than 1s. So what is the problem?
Because the call to defer pre-calculates the value of the function argument, i.e. the value of the argument time.Since(startedAt)
, rather than the value calculated after sleep has finished executing. This could be changed to match expectations
The defer followed by the anonymous function is sufficient and meets our expectations. The result of the execution is: 1.003861399s.
defer and panic
There are three times when the execution of a defer is triggered.
- The function wrapping the defer encounters return
- The function wrapping the defer is executed to the end
- when a panic occurs
Let’s look at what happens when a defer meets a panic.
No exceptions caught in defer when panic occurs
Running results.
Catch exception in defer when panic occurs
Running results.
There’s not much to say about the result of this example, a panic occurs and can be caught and handled in the defer function.
panic occurs in defer
The result is: catch inner panic. i.e. panic(“outer”) occurs in the outer layer, triggers the execution of the defer, panic(“inner”) occurs in the execution of the defer, and panic(“inner”) occurs in the last The panic is caught in the defer, and the last panic is caught.
Also, try not to use panic, and only use it if a non-recoverable error occurs or if something unexpected happens when the program starts.