3 ms·
If I am understanding him correctly: If defer were statically scoped, that is, if it were scoped to curly braces, you would "know" at compile time when and if a
by deathanatos 8y ago
If I am understanding him correctly: If defer were statically scoped, that is, if it were scoped to curly braces, you would "know" at compile time when and if a defer is going to run (relative to that scope). That is, a defer boils down to just "at the end of this scope, run this code" and nothing more, and all the compiler has to do is move that code/function call to the closing curly brace. (Similar to how a C++ compiler knows when to run a destructor for an object.)
However, by having them be function scoped, this isn't so anymore; e.g, a defer occurring in an if() statement needs to happen at the end of the function, but only if the if occurs. If you loop over a defer, we need to accumulate those. (And the golang tour even explicitly calls the behavior out.[1]) So, instead of just running the defer at the end of the if / inside the if statically, we need to push the defer onto a runtime stack of yet-to-be-run defers that we'll evaluate at the end of the function. This now has to happen at runtime, not compile time, and makes the function compilation more complex, and requires a stack somewhere to push this stuff onto.
From a compiler writer's perspective, I would agree w/ the parent: this seems much more complex, and runs counter to golang's otherwise simple design philosophy.
[1]: https://tour.golang.org/flowcontrol/13 https://tour.golang.org/flowcontrol/13