实现说明
逻辑集中在函数 buildReport、main里。
本示例的循环部分是 for name, count := range rows。
使用要点
- 直接运行文件,输出会带上标签,比如
total bytes:——输出的每一行都能指回产生它的那次调用。 main按顺序串起buildReport;运行文件就会把这个流程跑一遍。
常见问题
运行「Strings Builder 高效拼接」会打印什么?
运行文件本身,total bytes: 这些前缀各对应一段演示逻辑。
签名一览:func buildReport(rows map[string]int) string
核心语句
func buildReport(rows map[string]int) string {
var b strings.Builder
// Grow 预分配:已知大致体量时避免反复扩容
b.Grow(len(rows) * 24)
for name, count := range rows {
b.WriteString(name)
b.WriteByte(':')
b.WriteString(strconv.Itoa(count))
b.WriteByte('\n')
}
return b.String()
}
func main() {
rows := map[string]int{"requests": 1200, "errors": 3, "timeouts": 1}
report := buildReport(rows)
fmt.Print(report)
fmt.Println("total bytes:", len(report))
}
代码示例
package main
import (
"fmt"
"strconv"
"strings"
)
func buildReport(rows map[string]int) string {
var b strings.Builder
// Grow 预分配:已知大致体量时避免反复扩容
b.Grow(len(rows) * 24)
for name, count := range rows {
b.WriteString(name)
b.WriteByte(':')
b.WriteString(strconv.Itoa(count))
b.WriteByte('\n')
}
return b.String()
}
func main() {
rows := map[string]int{"requests": 1200, "errors": 3, "timeouts": 1}
report := buildReport(rows)
fmt.Print(report)
fmt.Println("total bytes:", len(report))
}