这种实现方式比使用 +=
要更节省内存和 CPU,尤其是要串联的字符串数目特别多的时候。
package main import ( "bytes" "fmt" ) func main() { a := [...]string{"a", "b", "c"} var buffer bytes.Buffer for _, v := range a { buffer.WriteString(v) } str := buffer.String() fmt.Println(str) buffer.Reset() str = buffer.String() fmt.Println(str) fmt.Println("343") for _, v := range a { buffer.WriteString(v) } buffer.Truncate(2) str = buffer.String() fmt.Println(str) for _, v := range a { buffer.WriteString(v) } buffer.Truncate(0) str = buffer.String() fmt.Println(str) }
// Reset resets the buffer to be empty,
// but it retains the underlying storage for use by future writes.
// Reset is the same as Truncate(0).
func (b *Buffer) Reset() {
b.buf = b.buf[:0]
b.off = 0
b.lastRead = opInvalid
}