Skip to content

Append formatted bytes with fmt.Appendf Has Fix

Description

Since Go 1.19, fmt.Appendf can format directly into a byte slice. It avoids creating an intermediate string with fmt.Sprintf and then converting that string to []byte. This rule matches only the exact nested append shape and keeps the buffer to a plain identifier.

It assumes fmt names the standard-library package and does not add the import.

YAML

yaml
id: use-fmt-appendf
language: Go
severity: hint
message: Append formatted bytes directly with fmt.Appendf.
rule:
  pattern:
    context: func f() { $BUFFER = append($BUFFER, []byte(fmt.Sprintf($$$ARGS))...) }
    selector: assignment_statement
constraints:
  BUFFER:
    kind: identifier
fix: $BUFFER = fmt.Appendf($BUFFER, $$$ARGS)

Example

go
import "fmt"

func appendCount(buf []byte, count int) []byte {
	buf = append(buf, []byte(fmt.Sprintf("count=%d", count))...)
	return buf
}

Diff

go
import "fmt"

func appendCount(buf []byte, count int) []byte {
	buf = append(buf, []byte(fmt.Sprintf("count=%d", count))...) 
	buf = fmt.Appendf(buf, "count=%d", count) 
	return buf
}

Credits

Based on JetBrains' Go Modern Guidelines.

Made with ❤️ with Rust