Strconv Append Writes Into Reused Buffers

Append numbers into one reusable byte buffer with strconv.AppendInt and AppendQuote, truncating with buf[:0] between rounds instead of allocating new strings.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"strconv"
)

func main() {
	buf := make([]byte, 0, 64)

	// Append* appends into reusable buffers; truncate with buf[:0] to reuse
	buf = strconv.AppendInt(buf, 2026, 10)
	buf = append(buf, '-')
	buf = strconv.AppendInt(buf, 11, 10)
	fmt.Println("date:", string(buf))

	buf = buf[:0]
	buf = strconv.AppendQuote(buf, "payload with \"quotes\"")
	fmt.Println("quoted:", string(buf))

	buf = buf[:0]
	buf = strconv.AppendFloat(buf, 3.14159, 'f', 2, 64)
	fmt.Println("float:", string(buf))

	buf = buf[:0]
	buf = strconv.AppendBool(buf, true)
	fmt.Println("bool:", string(buf))
}

What the demo reuses

One byte buffer with capacity 64 serves four conversions. strconv.AppendInt appends the digits of 2026 and 11 with a literal dash between them, and the first print shows date: 2026-11 assembled without allocating a single string.

Between rounds, buf = buf[:0] truncates the length while keeping the backing array, so AppendQuote, AppendFloat and AppendBool each overwrite the same memory. The Appends return the advanced slice header, which is why every result is assigned back to buf.

Practical notes

  • buf[:0] is the reuse trick: same array, fresh length.
  • AppendQuote escapes the embedded quotes the way strconv formats them.

Interactive Tools for This Topic

FAQ

Why assign the Append return value back to buf?
Append* take a slice and return the extended header; skipping the assignment drops any growth, mirroring the write-back rule for slice values.