8 ms·
A common idiom is the defer, for example, file.Close() only if there wasn't an error when the file was opened. You can also put them in an if statement. This
by rwj 8y ago
A common idiom is the defer, for example, file.Close() only if there wasn't an error when the file was opened. You can also put them in an if statement. This means that the deferred function aren't strictly tied to their scope.
Putting the defers on the stack is also part of how the runtime unwinds the stack during a panic.
- pcwalton 8y ago> Putting the defers on the stack is also part of how the runtime unwinds the stack during a panic. All exception ABIs on all major platforms can do this without any overhead in the no-exception case. The compiler embeds static metadata (in a subset of DWARF, on Linux) alongside the function, and the unwinder parses that metadata in order to determine which destructors to invoke.