Composite literals
Composite literals construct structs, arrays, slices, and maps directly, but keyedness and element rules matter for safety and readability.
Canonical guidance
- composite literals are type-directed constructors for aggregate values
- keyed elements improve resilience and readability for most non-local struct literals
- map, slice, array, and struct literals each have different rules
Use when
- checking initialization syntax
- reviewing struct literal readability
- explaining element or field errors at compile time
Avoid
- long positional literals for exported structs
- assuming keyedness rules are interchangeable across aggregate types
- relying on hidden zero values when a field matters semantically
Preferred pattern
u := User{ID: "42", Name: "Ava"}
Anti-pattern
- using a positional literal for a wide struct whose field order is easy to forget
Explanation: This is tempting because it is shorter, but the brevity is not worth the maintenance and review cost once the struct is non-trivial.
Why
- literal syntax is a frequent source of compile errors and brittle code at API boundaries