3 ms·
The defer keyword seems pretty cool. I assume it creates a stack of calls to execute just before exiting scope. Personally I find it a cool little syntactic su
by deevus 12y ago
The defer keyword seems pretty cool.
I assume it creates a stack of calls to execute just before exiting scope. Personally I find it a cool little syntactic sugar.
- gnuvince 12y agoGo has the same functionality, you should check it out. It's great, but I feel it's a "halfway solution": you open your file and then immediately add a `defer f.Close()` statement afterward, so you don't forget to close it in all exit paths of the function (i.e. early returns in branches), however you still need to remember to type the defer.
- ufo 12y agoIn functional languages you often see functions like with_file that use a closure to denote the file lifetime: with_file(fun file -> use_file(file) ) I wonder if there is a way to code something similar that works with "defer". This would free you from needing to "remember" to add the defer and would have the advantage of allowing you to use `return` and `break` statements which don't work if you wrap them inside an inner function. The only thing I can think of is Python's with statement. Since its language syntax it allows for `return` and `break` but I wonder if there is a way to play nice with defer instead of requiring you to use another "block level" syntax construct for every file you use.
- bjz_ 12y agoWe used to do this in Rust, but have found RAII much better for this. Dealing with multiple resources open at once can quickly become painful. See http://blog.skylight.io/rust-means-never-having-to-close-a-socket/#facilitiesinotherlanguages http://blog.skylight.io/rust-means-never-having-to-close-a-s...
- Too 12y agoSounds like the finally-keyword in most languages?
- bjz_ 12y agoHe does actually mention Go as the inspiration. Anyway, I still much prefer RAII for this - not only for guarding against your own forgetfulness, but also to make sure a rogue refactor or patch doesn't break anything.