← 中文资源

简体中文版本

用 strconv.AppendInt 在复用缓冲中格式化记录

使用 strconv.AppendInt 按十进制与十六进制把数值追加到预分配切片缓冲,每轮重置 buf[:0] 并验证底层容量始终未发生扩容。

阅读英文原文

实现说明

用 strconv.AppendInt 在复用缓冲中格式化记录可以归结为函数 formatEvent、main。 for _, s := range samples 承担全部的逐项处理。

使用要点

  • 结构高度独立——除开原生运行时内置模块之外再无其余导入。
  • 直接运行文件,输出会带上标签,比如 reused without realloc:——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 formatEvent。

常见问题

运行「用 strconv.AppendInt 在复用缓冲中格式化记录」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 reused without realloc: 这类标签。

入口签名:func formatEvent(dst []byte, seq, flags, latencyMs int64) []byte

核心语句

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)

代码示例

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)
}