Go

What does this program do?

Question 393HardGo 1.22 to 1.25
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

All 38 Performance, Profiling & Testing questions