Some Thoughts On String Interpolation [l10n, restricting access, AA]

kdevel kdevel at vogtner.de
Wed Nov 1 22:22:42 UTC 2023


On Saturday, 28 October 2023 at 13:13:16 UTC, Paul Backus wrote:
>> [...]
>> That typing is laborious. Isn't there a way to bind the 
>> expression to the keys of the AA?
>
> You can do this with existing language features: 
> https://run.dlang.io/is/QRFNpg

Amazing!

> Although I wouldn't really recommend it, since it forces you to 
> write fully-qualified names to access anything that *isn't* an 
> associative-array key.

The simple name (`x`) seems to work: 
https://run.dlang.io/is/Nzne84

```d
import std.stdio;

void main()
{
     string[string] aa;
     string x = "xxx";
     aa["name"] = "Arthur";
     aa["quest"] = "seek the Holy Grail";
     aa["favoriteColor"] = "blue";

     with (aa.keysAsVars)
     .writefln!"My name is %s, I %s, and my favorite color is %s."(
     	name, quest, x);
}

struct KeysAsVars(K, V)
{
     V[K] aa;
     V opDispatch(string key)() => aa[key];
}

KeysAsVars!(K, V) keysAsVars(K, V)(V[K] aa)
{
     return typeof(return)(aa);
}
```


More information about the Digitalmars-d mailing list