I really do not like code like
defer func() {
if cerr := f.Close(); cerr != nil && err == nil {
err = cerr
}
}()
My problem with this code is:
1) It is ugly
2) It is too clever
3) It is not clear what the code actually does
4) It is a trap for maintainers of the code
This code _seems_ to pass any error returned by f.Close() to the enclosing function.
But it only works if the function has a named return parameter. If somebody later
changes the function to return unnamed values, this defer will silently fail.
This happens all the time out in the wild.
(Check out
https://github.com/blevesearch/bleve/blob/369ad22b9fefdadb42b9367193ef7a73b9e5f4ff/search/searcher/search_regexp.go#L54for instance).
So my advice would be
1) Keep the code simple
2) Don't use defer in places where it leads to convoluted code.
3) It is often OK ignore the error returned by
f.Close()e.g. if f is a Reader, a bytes.Buffer, or a http.ResponseWriter.
- amnon