← 中文资源

简体中文版本

用 strings.Builder 增量拼文本

strings.Builder 在内部缓冲上追加,Grow 预留容量减少扩容,Reset 清空内容但保留底层缓冲;每次 + 拼接都复制整段,循环拼接必须改用 Builder。

阅读英文原文

实现说明

整个示例围绕函数 render、main组织。 for i, row := range rows 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 演示输出是带标签的(len:),每个操作都会留下自己的一行标注。
  • 执行文件,main 会按顺序走完 render。

常见问题

运行「用 strings.Builder 增量拼文本」会打印什么?

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

入口签名:func render(rows []string) string

核心语句

func render(rows []string) string {
	// Builder appends into one internal buffer, avoiding a full copy per + concatenation
	var b strings.Builder
	b.Grow(64) // preallocate capacity to reduce regrowth
	for i, row := range rows {
		if i > 0 {
			b.WriteString(", ")
		}
		b.WriteString(row)
	}
	return b.String()
}

代码示例

package main

import (
	"fmt"
	"strings"
)

func render(rows []string) string {
	// Builder appends into one internal buffer, avoiding a full copy per + concatenation
	var b strings.Builder
	b.Grow(64) // preallocate capacity to reduce regrowth
	for i, row := range rows {
		if i > 0 {
			b.WriteString(", ")
		}
		b.WriteString(row)
	}
	return b.String()
}

func main() {
	fmt.Println(render([]string{"alpha", "beta", "gamma"}))

	// Length and capacity are separate: after writing four words the length no longer equals the capacity
	var a strings.Builder
	a.WriteString("keep")
	fmt.Println("len:", a.Len(), "cap:", a.Cap())

	// Reset empties the content but keeps the underlying capacity, so the buffer is reusable
	a.Reset()
	a.WriteString("again")
	fmt.Println(a.String())
}