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.
Code
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
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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.