liveBook · Manning

Closer

As explained in 100 Go Mistakes and How to Avoid Them

io.Closer is a Go interface whose Close method releases or terminates an associated resource and returns an error.

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

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines the single-method interface and works through deferred-error handling, logging, propagation, and error precedence.
Examples
Uses database rows, os.File, deferred closures, logging, named errors, and synchronous file writes as concrete cases.
What it assumes
Assumes familiarity with Go errors and defer while teaching the Close contract and cleanup-error decisions through examples.
What you can do after
Diagnose/debug with it by tracing deferred Close calls and choosing whether to ignore, log, or propagate their errors.
How it connects
Connects resource leaks, defer, named return parameters, database rows, file synchronization, and error propagation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.