io.Closer is a Go interface with one method, Close() error. Types use it to signal that an associated transient resource must eventually be closed. section 7.7 section 10.5
type Closer interface {
Close() error
}
The minimal interface makes the resource-lifecycle contract explicit. section 10.5
A common mistake is deferring Close without considering its returned error. Ignoring a close failure can hide a failed database cleanup or an unreleased connection. section 7.7
Choose the handling strategy according to the consequence of closing failure:
- Mark an intentionally ignored error explicitly with defer func() { _ = rows.Close() }(). section 7.7
- Log the failure when awareness is sufficient, such as when closing database rows or a file fails. section 7.7 section 10.5.3
- Propagate the close error through named result parameters when cleanup failure should reach the caller. section 7.7 section 10.5.3
- Preserve an earlier operation error while recording Close only when no earlier error exists. section 7.7 section 10.5.3
Closing database rows
After a successful query, defer rows.Close(). If cleanup errors matter, use a deferred function that assigns the Close result to a named err return; otherwise log or explicitly discard it. section 7.7
Synchronous file writing
A file-writing function can defer Close and return f.Sync() after the write when durability matters; in that synchronous case, Close errors can safely be ignored. section 10.5.3
