Access Variable (or Variable Values) using String Variable Name

I’m working through the Advent of Code problems. One of them involves keeping track of directional moves, given as strings (“N”, “S”, “E”, “W”) and integer values. I’ve set up variables N, S, E, and W to track movement. Passing on whether this is a sensible way to solve this part of the problem, I’d like to be able to use the string values to access the same-named variables. For example, if I have (“N”, 30) as input, I can add 30 to the value of N without having to write out if x == "N" N += 30 for every directional string letter.

I’ve tried using a Dictionary and Symbols, but I suspect this involves a metaprogramming/macro solution. I researched how to to accomplish this online, and read the Julia “metaprogramming” docs, but the solution isn’t coming to me. Any help would be appreciated. I know this is something that Julia ought to be able to do.

Thank you!

I think a NamedTuple or Enumwould be what you want here. No meta-programming necessary


You might want to use symbols :N, :S etc, instead of strings.
A dictionary then seems like a perfectly good (although probably not optimally fast) solution.

1 Like

Thanks both of you, I realize I was over-complicating the problem. The solution (a regular old-fashioned Dict) was so simple that I couldn’t see it. Slow progress …