Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Go has defer, so you can write:

   f = os.Open(...)
   defer f.Close()
   // do stuff with f...
This ensures you close the file at the end of the scope. If processing the file is complex, with lots of places where return is called, then there's lots of places where the Close call could actually need happen. Thankfully you just write it once with defer, and you can forget about it.

In languages without defer you need something else. The RIIA approach is to create a file object where the constructor opens the file and the destructor closes the file. The compiler needs to track the file objects scope in order to call the destructor. This acts as a hook to run some code right at the end of the scope, wherever that actually occurs.

Both call close right before returning, but the actual mechanism is different because the languages have different tools.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: