defer is a LIFO or a stack - it is guaranteed to execute in the reverse order. It gets the first defer and puts it on some internal stack (maybe I don’t know the gory details), and then puts the next defer on top of it, and then when it hits the end of the function, it unwinds, starting from the top. This seems to have been done in for -loop (I know this is an Go example, not yours), but in other cases where one function depends on cleaning up some other function, it makes more sense why it MUST be, and therefore, IS, guaranteed reverse order execution.
Here is another example, the whole pseudo-code, but, hopefully, the point is clear.
open stream1 defer close stream1 defer write stream1 "stream2 better be closed, or we are in trouble..." open stream2 defer close stream2 defer stream2 "this is the last you'll ever hear from stream2" connect stream2 to stream1 write stream2 "hey, we are in stream2, this feeds into stream1"
Should print something like:
"hey, we are in stream2, this feeds into stream1" "this is the last you'll ever hear from stream2" "stream2 better be closed, or we are in trouble..."
Unless you had guarantees regarding the return order, you could not be sure that stream1 was still open during your defer stream2 write .
dwanderson May 6 '16 at 1:27 pm 2016-05-06 13:27
source share