String Interpolation

Arafel er.krali at gmail.com
Sat Oct 21 16:30:07 UTC 2023


On 21/10/23 17:42, Commander Zot wrote:
> you are missing the point. if |i""| does behave differently from just 
> |""| this will lead to a huge number of people being confused later. 
> they should really both be strings, or i"" should not exist at all. if 
> you want interpolated tuples don't call it string interpolation and use 
> t"" instead. changing code from "" to i"" should not change it's behavior.

I also think that interpolated strings should behave like... well, 
strings. Anything else would break the principle of least astonishment, 
and it's not certainly what some people might expect, me among them. If 
you must do it, please just don't call it "interpolated **string**".

Be it Python, Perl, bash, C# and even JavaScript (AFAIK, I've got less 
experience there), when you interpolate a string you get... well, a 
string. Only JS is more flexible here, but by default you'll get a string.

Even if they are not strings under the hood, they should be implicitly 
convertible to strings, at least in the default implementation, so if I 
have:

```
void foo(string s);
```

I should be able to do:

```
foo(i"Hello, $(name)");
```

or whatever other syntax is agreed upon, I don't really care that much 
about the bikeshedding.

Of course it's going to allocate when used like this, but it is a 
_convenience_ feature... The same way appending to a slice might 
allocate, those worried about allocations or using @nogc will have to 
take care of this, it's just syntactic sugar, after all.

Now, if under the hood there is something that library authors can 
override, that would be cool, but this "something" could just be a 
templated struct with an alias this to string. AFAIK the more specific 
match to the struct would then be the preferred overload.

I know `alias this` is kind of frowned upon, but I think this kind of 
usage is exactly what it is useful for:

```
void foo(string s) { }
void foo(IS)(IS s) if (isInterpolatedString!IS) { }
```

If a library author doesn't want a raw string and only support a 
specific interpolated string format, they just need to remove the first 
overload.


More information about the Digitalmars-d mailing list