Managing file reading, closing + buffer allocation and deallocation

Because you want to close the file in two separate contexts (once you are done and when there was an error), you could also declare it as var file: ?File and, when closing, check if it is valid:

errdefer { if (file) |f| { f.close(); f = null; }
// do stuff
...
// eagerly close the file:
if (file) |f| { f.close(); f = null; }
// do more stuff, file is now closed
...
1 Like