errors.New(fmt.Sprintf(...)) can be written as fmt.Errorf(...)

tx0/go:errors-new-sprintfstrictwarningstyle

What it finds

errors.New(fmt.Sprintf(format, args...)), which fmt.Errorf(format, args...) says in one call.

fmt.Errorf returns errors.New of the formatted text unless the format has a %w verb, so the fix is safe when the format is a constant without one. With another format the fix is offered as unsafe, since %w would then wrap an error instead of printing %!w.

From the rule's source, errors_new_sprintf.rs.

Example from the rule's tests
package p import (	"errors"	"fmt"	f "fmt") func check(name string, n int, format string) error {	if n == 0 {		return errors.New(fmt.Sprintf("%s: empty", name))tx0 reports: this can be written as fmt.Errorf(...)	}	if n == 1 {		return errors.New(f.Sprintf("%s: %d", name, n))tx0 reports: this can be written as f.Errorf(...)	}	if n == 2 {		return errors.New(fmt.Sprint(name))	}	if n == 3 {		return errors.New(name + fmt.Sprintf("%d", n))	}	{		fmt := fake{}		return errors.New(fmt.Sprintf("%d", n))	}} type fake struct{} func (fake) Sprintf(string, ...any) string { return "" }
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 strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/go:errors-new-sprintf" = "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:errors-new-sprintf] reason="..."

tx0 explain tx0/go:errors-new-sprintf shows the same in the terminal. Found a false positive? Report it.