Addressing defer Warnings from Golang errcheck
Overview
When you write code like the following and run errcheck, it flags defer f.Close().
1 | func hoge() error { |
The warning says that f.Close() returns an error, and that error return value is not being checked.
Solution
To work around this, you can fix it as follows.
1 | func hoge() error { |
However, in the case above, a panic occurs when an error happens.
If you use log.Println instead, the error does get logged, but you cannot handle subsequent processing based on that error.
So I tried fixing it further as shown below.
1 | func hoge() (err error) { |
With the following steps, you can return the error from f.Close() as the return value of hoge().
- Specify a named return value
err errorin the return values of thehoge()function - Store the
errorreturned byf.Close()intoerrinside the deferredfunc(){}
References
This topic had already been discussed quite a while ago.
Addressing defer Warnings from Golang errcheck
https://kenzo0107.github.io/en/2019/12/09/golang-errcheck-defer/