Home > Article > Backend Development > How to Safely Defer Functions with Potentially Unchecked Return Values in Go?
Managing Deferred Functions with Unchecked Return Values
When using gometalinter and errcheck, developers may encounter warnings about deferring functions that return a variable without checking for errors. This typically occurs in scenarios like closing a request body, where the Close() method returns an error value.
To address this issue, the recommended approach is to defer another function that calls the original function and checks its return value. This can be achieved using an anonymous function, as follows:
<code class="go">defer func() { if err := r.Body.Close(); err != nil { // Handle the error } }()</code>
An alternative solution is to create a helper function that performs the error checking:
<code class="go">func Check(f func() error) { if err := f(); err != nil { // Handle the error } }</code>
This helper function can then be used to defer the original function:
<code class="go">defer Check(r.Body.Close)</code>
For multiple deferred functions, a modified helper can be created to accept an array of functions:
<code class="go">func Checks(fs ...func() error) { // Implement error checking and execution logic }</code>
Using this helper:
<code class="go">defer Checks(r.Body.Close, SomeOtherFunc)</code>
The downward loop in the Checks() helper ensures that the last deferred function is executed first, preserving the execution order of deferred functions.
The above is the detailed content of How to Safely Defer Functions with Potentially Unchecked Return Values in Go?. For more information, please follow other related articles on the PHP Chinese website!