Defering execution of code is commonly used in Go to clean up resources. It's not so often seen but happens that defer
is used to execute regular business logic, too. Just as a last step of execution, no matter at which point function hits return
keyword.
On Go Blog page, we can find that "defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions."
They do mention about cleaning up but nothing about regular code execution. Obviously, it may execute an arbitrary code, doesn't have to be cleaning up. Is this the best practice, though? Has community any agreement on convention or best practice in this regard?
The Go compiler doesn't know what code is clean-up code. So if it works to defer clean-up code, it will obviously work to defer any non-clean-up code too.
There is some overhead for deferred functions, obviously the call stack has to be managed, but if it makes your code safer and / or easier to read, go for it. It's perfectly fine to use it to do any action before a return, even to modify the values being returned, and even in case of panicing. See How to return a value in a Go function that panics?
One thing you should keep in mind: deferred functions are run even if the code panics (which is desirable for clean-up code), which otherwise would not be a normal flow of execution. So this will be a difference when using defer compared to not using it. See related: `defer` in the loop - what will be better?