3 ms·
Could you, please, expand on double closing? I can't find any good reason to do it.
by wst_ 7y ago
Could you, please, expand on double closing? I can't find any good reason to do it.
- klodolph 7y agoOn a file open for writing, close(2) may return EIO. If you ignore the error, you have silent data loss. So you must propagate the error. The double-close pattern is just the easy way to accomplish this in go. You defer fp.Close(), and then return fp.Close(). The return fp.Close() closes the file and propagates the error. Afterwards, the deferred fp.Close() executes, but this simply returns an error (which is ignored) because the file is already closed. The behavior of fp.Close(), the fact that it is safe to call multiple times, is documented in the Go documentation. There are alternative ways to achieve the same effect but they require more code. So I use the double-close pattern everywhere, and then put a comment in every time I use it.