Map — heterogeneous key-value store with runtime type checking. Struct — homogeneous collection of named fields with compile-time type checking.
Maps are ideal when keys are not known ahead of time. They use hash tables internally, giving O(1) average-case lookups. Maps are reference types — passing one to a function shares the same data.
1config := map[string]string{2 "log_level": "debug",3 "port": "8080",4}5config[os.Getenv("KEY")] = os.Getenv("VALUE") // dynamic key
Structs give you compile-time safety — the compiler knows every field name and type. This catches typos, enables IDE autocompletion, and makes code self-documenting.
1type Config struct {2 LogLevel string `json:"log_level"`3 Port string `json:"port"`4}56cfg := Config{LogLevel: "debug", Port: "8080"}7cfg.Log_level = "info" // compile error — typo caught!
When to use:
Common mistakes:
map[string]interface{} to model complex data — use a struct with json tags.ok value — silently returns zero value.== (except against nil).