← 中文资源

简体中文版本

用 fmt.Appendf 追加格式化字节

fmt.Appendf 把格式化结果追加进可复用的字节缓冲,省掉 Sprintf 每次分配新字符串的开销,追加后还能继续用普通 append 拼接。

阅读英文原文

实现说明

用 fmt.Appendf 追加格式化字节以函数 main为骨架。 迭代发生在 for i, user := range []string{"ada", "grace", "linus"} 内部——循环之外的语句只执行一遍。

使用要点

  • 跑完文件,输出里会留下标记——sprintf:。

常见问题

运行「用 fmt.Appendf 追加格式化字节」会打印什么?

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

核心语句

for i, user := range []string{"ada", "grace", "linus"} {
	// fmt.Appendf appends the formatted result to buf and returns the new slice
	buf = fmt.Appendf(buf, "%02d user=%s;", i+1, user)
}
s := fmt.Sprintf("%02d user=%s;", 1, "ada")
buf = append(buf, []byte("done")...)

代码示例

package main

import "fmt"

func main() {
	// a reusable byte buffer: formatted bytes append onto the same backing array
	buf := make([]byte, 0, 64)

	for i, user := range []string{"ada", "grace", "linus"} {
		// fmt.Appendf appends the formatted result to buf and returns the new slice
		buf = fmt.Appendf(buf, "%02d user=%s;", i+1, user)
	}
	fmt.Println(string(buf))

	// compare fmt.Sprintf: every call allocates a brand-new string
	s := fmt.Sprintf("%02d user=%s;", 1, "ada")
	fmt.Println("sprintf:", s)

	// after appending, plain append can keep joining raw bytes, then another formatted chunk
	buf = append(buf, []byte("done")...)
	buf = fmt.Appendf(buf, " total=%d", len(buf))
	fmt.Println(string(buf))
}