What does this program do?
package main
import (
"fmt"
"strings"
)
func main() {
var a strings.Builder
a.WriteString("hello")
b := a
b.WriteString(" world")
fmt.Println(b.String())
}
It panics: strings: illegal use of non-zero Builder copied by value.
A strings.Builder stores a pointer to itself (addr) on first write. Every write checks b.addr == b; the copy b still has a's address, so the check fails. The reason for the guard: String() returns the internal byte slice as a string without copying (via unsafe.String). If two builders shared the same backing array, writing to one could mutate a string previously returned by the other — breaking string immutability.
Copying a zero Builder is fine. Correct usage: pass *strings.Builder to functions, or accept an io.Writer/io.StringWriter. go vet's copylocks check doesn't catch this (Builder has no Lock method), so it's a runtime panic. Interviewer is looking for: understanding why Builder's String() is zero-copy and what invariant that requires — the same reasoning applies to bytes.Buffer.Bytes(), which aliases internal storage until the next mutation.
More on Performance, Profiling & Testing
- Q391What are the tradeoffs of sync.Pool? When does it help, and when does it hurt?
- Q392Compare the performance of string concatenation approaches: +, fmt.Sprintf, strings.Builder, bytes.Buffer, strings.Join.
- Q394How do GOGC and GOMEMLIMIT interact, and how would you tune the GC for a latency-sensitive service?
- Q395Why does preallocating slices and maps matter? What does this print?
- Q396What is false sharing and how would you detect and fix it in Go?
- Q397How does struct field ordering affect memory usage and performance?