Format Records Into Reused Buffers With AppendInt
Build structured telemetry lines in a preallocated byte slice using strconv.AppendInt for decimal and hex fields while keeping buffer capacity fixed.
Code
package main
import (
"fmt"
"strconv"
)
func formatEvent(dst []byte, seq, flags, latencyMs int64) []byte {
dst = append(dst, "seq="...)
dst = strconv.AppendInt(dst, seq, 10)
dst = append(dst, " flags=0x"...)
dst = strconv.AppendInt(dst, flags, 16)
dst = append(dst, " ms="...)
dst = strconv.AppendInt(dst, latencyMs, 10)
return dst
}
func main() {
buf := make([]byte, 0, 64)
initialCap := cap(buf)
samples := []struct {
seq int64
flags int64
ms int64
}{
{101, 0x1a, 12},
{102, 0x0f, 45},
{103, 0xff, 7},
}
for _, s := range samples {
buf = formatEvent(buf[:0], s.seq, s.flags, s.ms)
fmt.Printf("%s (len=%d cap=%d)\n", buf, len(buf), cap(buf))
}
fmt.Println("reused without realloc:", cap(buf) == initialCap)
}Implementation trace — Format Records Into Reused Buffers With AppendInt
Format Records Into Reused Buffers With AppendInt reduces to the functions formatEvent and main.
for _, s := range samples handles iterative traversal across each item cleanly.
Caveats
- Fully standalone snippet — uses purely bundled modules native to the runtime.
Using it
Signature: func formatEvent(dst []byte, seq, flags, latencyMs int64) []byte
The file’s steps show up in the output as reused without realloc:.
There are 1 call inside main — formatEvent — executed top to bottom.
Key statements
func formatEvent(dst []byte, seq, flags, latencyMs int64) []byte {
dst = append(dst, "seq="...)
dst = strconv.AppendInt(dst, seq, 10)
dst = append(dst, " flags=0x"...)
dst = strconv.AppendInt(dst, flags, 16)
dst = append(dst, " ms="...)
dst = strconv.AppendInt(dst, latencyMs, 10)
return dst
}
for _, s := range samples {
buf = formatEvent(buf[:0], s.seq, s.flags, s.ms)
fmt.Printf("%s (len=%d cap=%d)\n", buf, len(buf), cap(buf))
}
buf := make([]byte, 0, 64)
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.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.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.
FAQ
- What does Format Records Into Reused Buffers With AppendInt print when run?
- Running the file directly is enough — expect labeled output lines such as `reused without realloc:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.