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 safety
Critical 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.
More Related questions...