4 ms·
Go's defer is verbose and unwieldy compared to Python's `with` statement or Rust's lifetime system. In Python, you don't have to manually write any code to clos
by EnergyAmy 3y ago
Go's defer is verbose and unwieldy compared to Python's `with` statement or Rust's lifetime system. In Python, you don't have to manually write any code to close the file, you just do:
with open('foo') as f:
...
And the file will be closed after that block of code finishes executing. Similarly in Rust if you do "let file = File::open("foo")?;", when the variable drops the file will be closed.
If you want to loop over 10k files, both of those handle that just fine, because the active file will be closed at the end of each loop. Go's defer will try to wait until after the loop to close everything. You can make things even more verbose to fix that, but it gets ugly real quick.
- arp242 3y agoI wish defer was block-scoped rather than function-scoped; that would solve the "defer in a loop" problem. Right now I just wrap the lot in a function for that, which works and isn't too bad, but meh. defer is more flexibly and explicit though; I rather like that. It's pretty unclear what exactly that "with" does, what you can and can't use inside "with", you can't "just" run any arbitrary code without creating your own class, and you sometimes end up with 3 or more levels of nested "with"s that could have been one defer. In short, I don't think there's a clear winner. Both are clunky in some scenarios where the other is easier.