Introduction
The defer statement helps you run some code right before a function ends. It is useful to clean up things like closing files or freeing resources, no matter how the function finishes.
When you open a file and want to make sure it closes before leaving the function.
When you allocate memory or resources and want to release them safely at the end.
When you want to run some cleanup code even if an error happens or the function returns early.
When you want to keep your cleanup code in one place at the end of a function for clarity.