3 ms·
I avoid using defer
by dana321 8y ago
I avoid using defer
- sagichmal 8y agoThat seems dumb; `defer` is an excellent and idiomatic tool for many use cases, principally but not exclusively resource cleanup.
- echlebek 8y agoThe other commenter wasn't very kind towards you, but I'd definitely encourage you to use defer to get correct semantics around releasing resources. It's the best tool that the language gives you for that.
- dana321 8y agoSorry, but for me its not a great method of releasing resources. I tend to (for example) open a connection in one function, do something with it in another function, close it in another. I'm not writing traditional go programs, i wrap things in an api.
- echlebek 8y agoSounds like that practice would make resource lifetimes hard to reason about. And without defer, you don't have the opportunity to clean up resources if a goroutine panics.
- kazinator 8y agoThe higher level procedure which uses these three functions could use defer to ensure that the closing function is called.
- dana321 8y agoI would have to re-arrange my call stack so that the read or write functions would be inside the open statement, then it would close it at the end anyway so its kind of pointless for my uses. I try and totally avoid panics and never throw them unless its at some initial parser stage. But this is made me rethink the structure of how some of my tags operate in my interpreter / transpiler.