← 中文资源

简体中文版本

strconv Append 系列写复用缓冲

strconv.AppendInt、AppendQuote、AppendFloat、AppendBool 把结果追加进缓冲并返回新切片头;用 buf[:0] 截断复用同一块内存,热路径上避免反复分配字符串。

阅读英文原文

运行说明

一个容量 64 的字节缓冲服务四次转换。strconv.AppendInt 追加 2026 与 11 的数字位,中间放一个连字符,第一次打印得到 date: 2026-11,全程没有分配字符串。

每轮之间 buf = buf[:0] 只截断长度、保留底层数组,AppendQuote、AppendFloat、AppendBool 依次复用同一块内存。Append 系列返回推进后的切片头,所以每次结果都要赋回 buf。

要点提示

  • buf[:0] 是复用技巧:同一个数组,长度归零。
  • AppendQuote 按 strconv 的规则转义内嵌引号。

核心语句

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

代码示例

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