[]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."> []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." />

Prev Next

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.

What is the critical risk of storing an unsafe.Pointer converted to uintptr in a variable?
What does unsafe.Sizeof(MyStruct{}) actually measure?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

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...

What is the internal structure of a Go slice and how does it differ from an array? How does append() work internally and what triggers a reallocation? When does a variable get allocated on the stack versus the heap in Go? How do goroutine stacks work and how do they grow in Go? How does Go's garbage collector work? Explain the tri-color mark-and-sweep algorithm. What are GOGC and GOMEMLIMIT and how do you use them to tune GC behavior? How are Go maps implemented internally and what does that mean for performance? When should you use sync.Map instead of a mutex-protected regular map? How do pointers work in Go and when should you pass by pointer vs by value? How does Go's goroutine scheduler work? Explain the GMP model. How are Go channels implemented internally? How are Go interfaces implemented internally and why do they matter for performance? How does Go's memory allocator work? Explain mcache, mcentral, and mheap. How are strings represented in Go and why are they immutable? How does defer work internally in Go and what are its performance implications? How do panic and recover work in Go and when should you use them? How do you profile a Go application using pprof? What is the Go race detector and how does it work? What is the difference between sync.Mutex and sync.RWMutex and when do you use each? When should you use channels versus mutexes in Go concurrency? How do generics work in Go 1.18+ and how do they affect performance? How does context.Context work and when do you use each context type? What is the 'unsafe' package in Go and when is it used? What is the nil interface pitfall in Go and how do you avoid it? What are goroutine leaks and how do you detect and prevent them? How does sync.WaitGroup work and what are common mistakes? How do closures capture variables in Go and what is the classic goroutine loop bug? How does struct embedding work in Go and how does it differ from inheritance? How does error wrapping work in Go 1.13+ with errors.Is and errors.As? How do you write and run benchmarks in Go? How does struct field ordering affect memory layout and performance in Go? How do you implement fan-out and fan-in patterns with Go goroutines? How does the reflect package work in Go and when should it be used? What is cgo in Go and what are its performance trade-offs? What does GOMAXPROCS control and how does it affect Go's concurrency model? How does sync.Once work and what are its use cases? What are the most common memory leak patterns in Go and how do you diagnose them? How do build constraints (build tags) work in Go? How do io.Reader and io.Writer work and why are they fundamental to Go's I/O model? What is the Go optimisation workflow? How do you go from a performance problem to a fix? What is sync.Pool and when should you use it? How do type assertions and type switches perform internally in Go? How does Go's module system work and what is the role of go.sum? How do you implement a worker pool in Go? What static analysis tools are essential for a Go project and what does each check?
Show more question and Answers...

GoLang Interfaces and Object Oriented Interview Questions

Comments & Discussions