Back to Concepts Roadmap
⚫ Level 6 — Memory Model
Memory Model

Memory Alignment & Struct Padding

Optimizing struct memory layout by ordering fields from largest to smallest.

Real-World Analogy (Mental Model)

Packing suitcases into a shelf with fixed 8-inch slots. Placing small items next to large ones without planning leaves empty gap padding.

Key Concepts & Rules To Remember

  • CPUs read memory in 4-byte or 8-byte word boundaries.
  • Misaligned fields cause compiler padding bytes.
  • Organize struct fields from largest size (8 bytes) to smallest (1 byte) to save memory.
Step-by-Step Code

1. Understanding Memory Alignment & Struct Padding

Optimizing struct memory layout by ordering fields from largest to smallest. In Go, memory alignment & struct padding is designed around clarity and high runtime efficiency.

example.goGo 1.24+
// ❌ Takes 24 bytes (with padding gaps):
type Bad struct { a bool; b int64; c bool }

// ✅ Takes 16 bytes (packed tightly):
type Good struct { b int64; a bool; c bool }

Common Beginner Pitfalls & Mistakes

Mistake: Misusing memory alignment & struct padding without understanding its memory or concurrency semantics.
✅ Correct Way: Always follow standard Go idioms and verify with tests.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

What is the primary concept behind Memory Alignment & Struct Padding?

Finished this lesson?

Mark it as complete to track your overall Go mastery.