The state of string interpolation

Adam D. Ruppe destructionator at gmail.com
Thu Dec 6 19:52:27 UTC 2018


On Thursday, 6 December 2018 at 18:41:34 UTC, Steven 
Schveighoffer wrote:
> Right, but it also requires that the callee deal with the 
> FromInterpolation type, no? Whereas just passing the tuple 
> doesn't require current code changes.
>
> I suppose FromInterpolation could alias itself to the actual 
> value. That way, it lowers to the original proposal.

Yes, with alias this it would work in most cases.

struct FromInterpolation(T) {
    string originalCode;
    T value;
    alias value this;
}

void main() {
   import std.stdio;
   string name = "adam";
   writeln("hi ", FromInterpolation!string("name", mixin("name")));
}


We can prove that works today by just writing it manually and 
running it. It also works for other types:

void foo(string s, string b);
foo("hi ", FromInterpolation!string("name", mixin("name")));


So I dare say in the majority of cases where you might use this, 
an alias this solution covers it. And if you DO want to 
specialize on the special data, it is there for you to use. (do a 
deconstructing is() expression to check if it is 
FromInterpolation and extract the type, then go crazy with it).


Passing the actual variable as a CT arg is doable.. but only if 
there IS an actual variable.

i"hi $(name)"; // could pass T!("hi ", name)
i"hi $(a+b)"; // error: cannot read variables at compile time


Now, maybe we don't want to support $(a+b)... but I think people 
would miss it. How many times in PHP or Ruby or whatever do we 
say:

"hi #{person["name"]}"

I think if we don't support that, people will see it as a 
crippled interpolation. So in my view, we get the most 
bang-for-buck by making it a runtime argument rather than a 
compile time alias.

(BTW it is interesting passing an int to a function with an 
interpolated string. but since it doesn't automatically convert 
and just does a tuple.. you can totally do that.)


More information about the Digitalmars-d mailing list