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.

GoCli Tooling

Code

gosnippet
23 lines
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

FAQ

What does Append Formatted Bytes With fmt.Appendf print when run?
The script runs standalone; its 1 labeled outputs include `sprintf:`.