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.

GoCli Tooling

Code

snippet
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

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:`.