About string and int spliced together.

Steven Schveighoffer schveiguy at gmail.com
Mon Aug 3 21:11:05 UTC 2020

On 7/31/20 2:18 PM, zoujiaqing wrote:
> On Friday, 31 July 2020 at 13:56:00 UTC, Steven Schveighoffer wrote:
>> what's complicated about:
>> string a = i"text $i!".idup;
> Thanks Steve.
> but about:
> string a = i"text $i!".idup;
> or:
> string a = "text" ~ i ~ "!";
> or:
> string a = "text {$i}!";
> I think the latter two are simpler ;)

So we have 2 alternatives here. Both are viable, and both have 
precedent. And without getting into the entire discussion again, I can 
tell you why I would not want them.

1. string a = "text" ~ i ~ "!";

For this to work, the compiler has to call a function to process i into 
string form. This could technically be done for integers without 
allocations. But in the general case it cannot:

string a = "text" ~ myStruct ~ "!";

Necessarily this has to be a conversion from the struct into a string, 
which then could be included in the concatenation. I'm not a fan of 
hidden allocations. I'd much rather see:

string a = "text" ~ myStruct.to!string ~ "!";

2. string a = "text {$i}!";

I'm sure you are aware that we will never see a feature just happen in 
existing strings like this. We absolutely need a marker for interpolated 
strings to distinguish interpolated strings from normal strings to 
prevent existing code breakage.

So I'm going to refashion this as another oft-requested idea, borrowing 
the DIP syntax a bit:

string a = i"text $i!";

The i prefix meaning "interpolated string".

Such a request is also reasonable. However, it's too meh. D has so much 
potential power with lowering and compile-time processing, that it would 
be a waste to force string interpolation this way. Yes, an important use 
case is creating a string on the heap with interpolated items, and 
assigning to a string. But for the extra suffix ".idup", you do get that 

AND if your goal is NOT just to create a string, there are far more 
efficient and useful things that can be had by the proposal:

writefln(i"text $i"); // just works
auto row = db.selectRow(i"SELECT * FROM tbl1 WHERE col1 = $i and col2 = 
$j"); // i and j passed as parameters to avoid sql injection

I WOULD be OK with an interpolated string automagically casting to a 
string, which converts into a library call for allocation. But this 
would really have to be something outside the normal type system. For 
avoiding the explicit ".idup" call, I think this is probably not worth 
it. And as Adam says in his DIP, the compiler can suggest using .idup 
when you should.

> Ref: https://www.php.net/manual/en/language.types.string.php

I use string interpolation in php all the time, mostly for SQL query 
writing. Super-prone to SQL injection, but I'm not going to change it now...


More information about the Digitalmars-d mailing list