Comment by hnlmorg
Really? I find the opposite is true. If I need lexical scope then I’d just write, for example
f.Close() // without defer
The reason I might want function scope defer is because there might be a lot of different exit points from that function.With lexical scope, there’s only three ways to safely jump the scope:
1. reaching the end of the procedure, in which case you don’t need a defer)
2. A ‘return’, in which case you’re also exiting the function scope
3. a ‘break’ or ‘continue’, which admittedly could see the benefit of a lexical scope defer but they’re also generally trivial to break into their own functions; and arguably should be if your code is getting complex enough that you’ve got enough branches to want a defer.
If Go had other control flows like try/catch, and so on and so forth, then there would be a stronger case for lexical defer. But it’s not really a problem for anyone aside those who are also looking for other features that Go also doesn’t support.
I don't write Go, but reading this, it feels like you don't actually need functional scoping at all. In Java, I would simply write:
try (SomeResource foo = SomeResource.open()) { method(foo); }
or
public void method() { try(...) { // all business logic wrapped in try-with-resources } }
To me it seems like lexical scoping can accomplish nearly everything functional scoping can, just without any surprising behavior.