The error of closing a file that was written is lost in a defer

tx0/go:unchecked-close-writerecommendedwarningbug, resources

What it finds

defer f.Close() for a file that the same function creates or opens for writing and then writes to. The error of Close is lost, and it is where some file systems report that buffered data could not be written.

f must be declared by f, err := os.Create(...) or by os.OpenFile with a flag written as os.O_WRONLY, os.O_APPEND, os.O_TRUNC or os.O_RDWR. A file opened only for writing counts as written when the function uses it for anything but closing; one opened with os.O_RDWR alone, only when the function calls one of its writing methods. A function that also calls f.Close() or f.Sync() elsewhere is assumed to check what matters. Ignoring the error is a reasonable choice for scratch files and logs, so the rule is recommended rather than on by default.

From the rule's source, unchecked_close_write.rs.

Example from the rule's tests
package p import (	"encoding/json"	"fmt"	"os") func save(path string, v any) error {	f, err := os.Create(path)	if err != nil {		return err	}	defer f.Close()tx0 reports: the error of f.Close is lost	return json.NewEncoder(f).Encode(v)} func appendLine(path, line string) error {	f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)	if err != nil {		return err	}	defer f.Close()tx0 reports: the error of f.Close is lost	_, err = fmt.Fprintln(f, line)	return err} func patch(path string, at int64) error {	f, err := os.OpenFile(path, os.O_RDWR, 0)	if err != nil {		return err	}	defer f.Close()tx0 reports: the error of f.Close is lost	_, err = f.WriteAt([]byte{0}, at)	return err} func inspect(path string) (int64, error) {	f, err := os.OpenFile(path, os.O_RDWR, 0)	if err != nil {		return 0, err	}	defer f.Close()	info, err := f.Stat()	if err != nil {		return 0, err	}	return info.Size(), decode(f)} func decode(*os.File) error { return nil }
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:unchecked-close-write" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/go:unchecked-close-write] reason="..."

tx0 explain tx0/go:unchecked-close-write shows the same in the terminal. Found a false positive? Report it.