7.8 defer Ordering: LIFO Stack of Deferred Calls
Right, so you’ve started sprinkling defer statements throughout your code like a responsible adult. You’re cleaning up your files, closing your connections, and unlocking your mutexes. It feels good, doesn’t it? Like you’re finally writing code that won’t leak resources all over the place. But now you’re starting to wonder: “Okay, but when exactly does this cleanup happen? And what if I have more than one?” Let’s cut to the chase. A defer statement doesn’t just run whenever it feels like it. It runs when the function that contains it returns. Not before, not after. But here’s the critical part you need to burn into your brain: deferred function calls are executed in Last-In-First-Out (LIFO) order. Think of it like a stack of plates. The last plate you put on the stack is the first one you take off.