Golang / Golang Internals and Memory Management Interview Questions
How are strings represented in Go and why are they immutable?
A Go string is a two-word struct similar to a slice header but without a capacity field: a ptr (unsafe.Pointer to the UTF-8 bytes) and a len (byte count). Strings are immutable ā the bytes they point to cannot be modified through any string operation.
// String header: {ptr unsafe.Pointer, len int}
s := "hello"
fmt.Println(len(s)) // 5 (bytes, not runes)
fmt.Println(s[0]) // 104 ā byte value of 'h'
// s[0] = 'H' // compile error: cannot assign to s[0]
// UTF-8: len counts bytes, range counts runes
emoji := "Go š"
fmt.Println(len(emoji)) // 7 (G=1, o=1, space=1, rocket=4 bytes)
for i, r := range emoji {
fmt.Printf("%d: %c\n", i, r) // i is byte offset, r is rune value
}
// String concatenation creates a NEW backing array each time
// Avoid in loops ā use strings.Builder instead
var b strings.Builder
for _, s := range words {
b.WriteString(s)
b.WriteByte(' ')
}
result := b.String() // single allocation
// string <-> []byte conversion
// Each conversion copies the bytes (different backing arrays)
bytes := []byte(s) // copy into a new mutable byte slice
s2 := string(bytes) // copy back ā new immutable string
// Zero-copy cast with unsafe (avoid unless in hot path + well-understood)
// Not recommended for general useImmutability allows strings to be safely shared without copying ā multiple strings can point to the same backing byte array (e.g., a slice of a longer string). String constants are interned into read-only memory in the binary, so no heap allocation is needed for them. The strings.Builder type avoids repeated allocation by maintaining a []byte buffer and converting to string only at the end.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
