The example above is contrived, and the code can be improved with some refactoring. But in the function, you can see that clean up code (stream.close()) has to be run at two places. This breaks the DRY principle, and is easy to miss when you modify the code. With the defer statement you can rewrite it:

The code in the defer block runs right before the function returns. So clean up code only appears once and is close to the initialization code, making it easier to reason. You can write multiple defer blocks in a function and they will be called in reverse order if you initialize multiple resources.

So use defer. Cleaner, fewer errors.

Your feedback is valuable:
Do you want more nuggets like this? Yes or No