Search code examples
macrosmetaprogrammingnim-lang

How do I access an object field via its field name in string form?


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?


Solution

  • 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!