Append Formatted Bytes With fmt.Appendf
Grow a reusable byte buffer with fmt.Appendf instead of fmt.Sprintf, so each formatted segment joins one backing array instead of allocating a new string.
Code
package main
import "fmt"
func main() {
// a reusable byte buffer: formatted bytes append onto the same backing array
buf := make([]byte, 0, 64)
for i, user := range []string{"ada", "grace", "linus"} {
// fmt.Appendf appends the formatted result to buf and returns the new slice
buf = fmt.Appendf(buf, "%02d user=%s;", i+1, user)
}
fmt.Println(string(buf))
// compare fmt.Sprintf: every call allocates a brand-new string
s := fmt.Sprintf("%02d user=%s;", 1, "ada")
fmt.Println("sprintf:", s)
// after appending, plain append can keep joining raw bytes, then another formatted chunk
buf = append(buf, []byte("done")...)
buf = fmt.Appendf(buf, " total=%d", len(buf))
fmt.Println(string(buf))
}How it works
Append Formatted Bytes With fmt.Appendf is built around the function main.
Repetition is confined to for i, user := range []string{"ada", "grace", "linus"} — the rest of the file is straight-line.
Putting it to use
The demo output is labeled (sprintf:), so every line of output can be traced to the operation that made it.
Core lines under the microscope
for i, user := range []string{"ada", "grace", "linus"} {
// fmt.Appendf appends the formatted result to buf and returns the new slice
buf = fmt.Appendf(buf, "%02d user=%s;", i+1, user)
}
s := fmt.Sprintf("%02d user=%s;", 1, "ada")
buf = append(buf, []byte("done")...)
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- What does Append Formatted Bytes With fmt.Appendf print when run?
- The script runs standalone; its 1 labeled outputs include `sprintf:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.