A string formatted with fmt.Sprintf is printed right away instead of formatting while printing

tx0/go:print-of-sprintfstrictwarningstyle, performance

What it finds

fmt.Println(fmt.Sprintf("%d items", n)): formatting into a string only to print the string makes an extra copy and hides the format from tools that check it against its arguments. fmt.Printf("%d items\n", n) does both at once; the same holds for Fprint and Fprintf.

Reported are calls of Print with the single argument Sprintf(...), and of Fprint with a writer and Sprintf(...), all of fmt, resolved through the imports. The fix calls Printf or Fprintf with the arguments of Sprintf, which prints the same, so it is safe. Println, which adds a newline, is reported without a fix.

From the rule's source, print_of_sprintf.rs.

Example from the rule's tests
package p import (	"fmt"	"os") func f(n int) {	fmt.Print(fmt.Sprintf("%d items", n))tx0 reports: fmt.Print prints a string that fmt.Sprintf just formatted	fmt.Println(fmt.Sprintf("%d items", n))tx0 reports: fmt.Println prints a string	fmt.Fprint(os.Stderr, fmt.Sprintf("%d", n))tx0 reports: fmt.Fprint prints a string	fmt.Printf("%d items\n", n)}
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:print-of-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:print-of-sprintf] reason="..."

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