Obtaining type and value of a variable named in another variable
Paul Backus
snarwin at gmail.com
Sun Oct 17 03:55:58 UTC 2021
On Sunday, 17 October 2021 at 02:42:54 UTC, Tejas wrote:
>
> Doesn't solve the compile-time only problem though :(
> The only solution I can think of is something with `variant`s,
> but it'll be messy.
Well, the fundamental issue is that in a language like D that
compiles to machine code, variable names only exist at compile
time. At runtime, the only thing you have is memory addresses
(pointers).
If you want to look something up by name at runtime, you will
have to use a data structure like an associative array:
```d
void main()
{
int[string] vars = ["fooVar": 4];
string strVar = "fooVar";
writeln(typeof(vars[strVar]).stringof);
writeln(vars[strVar]);
}
```
Of course, in this example, the associative array can only store
`int`s. If you want to store multiple types of data, you will
need to use a data type that supports runtime polymorphism, like
a class, a sum type, or a variant.
More information about the Digitalmars-d-learn
mailing list