0

I'm figuring out at compile-time the name of a specific field of an object that I want to access. Before I compile, I do not necessarily know which field that is going to be, so I just have that field name as a string. How can I leverage nim's metaprogramming to access that field on the object?

Philipp Doerner
  • 1,090
  • 7
  • 24

1 Answers1

2

You can write a very simple macro that evaluates to a dot expression (aka object.yourFieldNameString).

Here an example of how that can look like:

import std/[macros]

macro getField*(obj: object, fieldName: static string): untyped =
  nnkDotExpr.newTree(obj, ident(fieldName))

This will only work if you know the field at compiletime (aka when you have it as a static string)! Keep that in mind!

Philipp Doerner
  • 1,090
  • 7
  • 24