Obtaining type and value of a variable named in another variable

Paul Backus snarwin at gmail.com
Sun Oct 17 02:31:04 UTC 2021


On Saturday, 16 October 2021 at 23:07:22 UTC, DLearner wrote:
> ```d
> void main() {
>
>    import std.stdio;
>
>    int fooVar = 4;
>
>    string strVar;
>
>    strVar = "fooVar";
>    writeln(typeof(mixin(strVar)));
>    writeln(mixin(strVar));
> }
> ```
> Failed with 2x "Error: variable `strVar` cannot be read at 
> compile time".

You can fix this by making `strVar` a [manifest constant][1]:

```d
enum strVar = "fooVar";
writeln(typeof(mixin(strVar)).stringof);
writeln(mixin(strVar));
```

[1]: https://dlang.org/spec/enum.html#manifest_constants


More information about the Digitalmars-d-learn mailing list