Nim Macros: Compile-Time Getter/Setter Generation to Cut Boilerplate
Nim macros generate getter and setter methods at compile time, eliminating repetitive boilerplate without runtime overhead.
27 Aug 2026, 17:54 UTC

The Boilerplate Problem
When defining objects in Nim that need property access, developers often write repetitive getter and setter methods. For a type with several fields this boilerplate becomes tedious and error‑prone. Nim’s macro system can generate these accessors at compile time, removing the duplication.
How Nim Macros Work
Nim macros are procedures marked with the macro keyword. They receive the abstract syntax tree (AST) of their arguments during compilation and return new AST nodes. The compiler then treats the returned code as ordinary source.
- Compile‑time execution – no runtime overhead.
- AST manipulation – input and output are tree structures.
- Seamless integration – generated code looks like regular Nim to the compiler.
A Practical Getter/Setter Macro
macro genAccessors(T: typedesc): untyped =
for field in T.fields:
# getter
result.add quote do:
proc `field.name`*(obj: T): auto =
obj.`field.name`
# setter
result.add quote do:
proc `field.name`=(obj: var T; value: typeof(obj.`field.name`)) =
obj.`field.name` = value
Using the Macro
type Point = object
x: int
y: int
genAccessors(Point)
let p = Point(x: 10, y: 20)
echo p.x # getter
p.x = 15 # setter
echo p.y
p.y = 25
Debugging Generated Code
- View expanded AST:
nim c -d:showCodeGen prog.nim - Inspect generated C:
nim cpp -d:release prog.nim - Use the VM dump for macro expansion details.
Trade-offs and Limitations
- Debugging complexity – generated code isn’t visible in the source; special flags are needed.
- Learning curve – newcomers may find macro‑heavy code harder to follow.
- Version requirement – full
typedescsupport needs Nim 2.0.0 or later.
Verification Checklist
- Check Nim version:
nim --version(requires 2.0.0+). - Compile with code‑gen visible:
nim c -d:showCodeGen prog.nim. - Run the executable to confirm getter/setter behavior.
- If needed, examine the C output:
nim cpp -d:release prog.nim.
Macros let you eliminate repetitive boilerplate while keeping zero runtime overhead, producing concise and maintainable Nim code.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.