Golang / Golang Internals and Memory Management Interview Questions
What is the 'unsafe' package in Go and when is it used?
The unsafe package lets Go code step outside the type system and interact with raw memory. Its functions and types are special — the compiler handles them intrinsically. Using unsafe bypasses garbage collection safety and may break with future Go versions, so it should be used only in well-justified, carefully tested situations.
import "unsafe"
// unsafe.Sizeof — size of a type in bytes (compile-time)
type MyStruct struct {
a int32 // 4 bytes
b int64 // 8 bytes (8-byte aligned)
c int8 // 1 byte
// 7 bytes padding to next 8-byte boundary
}
fmt.Println(unsafe.Sizeof(MyStruct{})) // 24 (not 13!) — alignment padding
fmt.Println(unsafe.Alignof(MyStruct{}.b)) // 8
fmt.Println(unsafe.Offsetof(MyStruct{}.b)) // 8 (offset of field b)
// unsafe.Pointer — the 'escape hatch' for type-unsafe pointer conversion
// uintptr + unsafe.Pointer can do pointer arithmetic
// But: converting to uintptr makes the value opaque to GC — GC can move object!
// Zero-copy string <-> []byte (HIGH RISK — avoid in application code)
// Only safe when the lifetime and mutability constraints are guaranteed
func bytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// Struct field access via offset (used in reflect, cgo, sync internals)
// go:linkname — link to unexported symbols in other packages
// (used by stdlib, not for general use)
// Safe uses of unsafe:
// - Measuring struct size/alignment for documentation
// - Implementing generic data structures that need raw memory (arena allocators)
// - cgo interoperability
// - Performance-critical zero-copy conversions with proven safetyCritical GC hazard: when you convert unsafe.Pointer to uintptr, the GC no longer tracks it as a pointer — if the GC runs, it may move the object and the uintptr becomes a dangling reference. Always convert back to unsafe.Pointer in the same expression, never store a uintptr temporarily.
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...
