DEV Community

Quinton Juma
Quinton Juma

Posted on

Maps vs. Structs: Are you using the right tool for the job?

It’s easy to reach for maps when structuring data, but using them where structs belong introduces silent bugs, memory overhead, and unmaintainable code.

Here is why Structs do what Maps simply cannot:

Compile-Time Safety: Catch field typos (user.Email vs user["emial"]) at compile-time, not in production.

Performance & Memory: Structs use contiguous memory offsets—zero hash calculations, lower CPU overhead, and less GC pressure.

Explicit API Contracts: Self-documenting types mean no guessing what fields a function expects or dealing with continuous type assertions (.(string)).

Heterogeneous Types: Mix ints, strings, and custom types cleanly without resorting to dynamic any / interface{} wrappers.

Quick Rule of Thumb:
Use Maps for dynamic, unpredictable keys (like caches or word counts). Use Structs for fixed domain models, API payloads, and configured schemas.

Top comments (0)