TIL about fmt.Appendf
Mon, Nov 24, 2025
One-minute read
TIL about fmt.Appendf
Turn this:
request := []byte(fmt.Sprintf(`{"request_id":%d}`, rand.Int63()))
Into
request := fmt.Appendf(nil, `{"request_id":%d}`, rand.Int63())
I really like this; much simpler to type and quite clean in mu opinion.
Another benefit is reduced allocations. It allows us to extend a byte slice instead of generating new ones.
The source is quite easy to understand IMO
// ref: https://cs.opensource.google/go/go/+/master:src/fmt/print.go;l=247
// Appendf formats according to a format specifier, appends the result to the byte
// slice, and returns the updated slice.
func Appendf(b []byte, format string, a ...any) []byte {
p := newPrinter()
p.doPrintf(format, a)
b = append(b, p.buf...)
p.free()
return b
}
Tags:
#go #til