Interpolated strings
Jonathan Marler via Digitalmars-d
digitalmars-d at puremagic.com
Wed Apr 19 06:04:08 PDT 2017
On Wednesday, 19 April 2017 at 12:03:47 UTC, Stefan Koch wrote:
> On Wednesday, 19 April 2017 at 11:59:51 UTC, Jonas Drewsen
> wrote:
>
>> What about supporting an optional prefix inside the {} like:
>>
>> int year = 2017;
>> format($"The date is {%04d year}");
>>
>> so if there is a % immediately following the { then the chars
>> until next whitespace is format specifier. You can of course
>> leave out the format specifier and it will default to %s.
> I really don't see how string interpolation is better then
> ` "The date is " ~ format("%04d", year)); `
I can think of 3 reasons.
1. Requires GC.
NOTE: I believe that most applcations should use GC memory, that
being said, library code has to be nogc wherever it can if it
wants to be used by nogc apps, so this solution is unusable in
alot of library code.
2. It's verbose. Jonas provided a good example of why and he
makes a good point that your example only has 1 formatted
argument and this problem gets much worse with multiple.
3. The biggest reason I wouldn't use this solution because it
uses string composition. String composition wastes memory and
memory management cycles. And when I say "waste" what I mean is,
the use is unnecessary. In general composition is a powerful
tool because it allows you to easily overload and abstract and
add new functionality, however, it requires runtime overhead.
This is the reason that the toString(delegate) was created to
replace the composable toString paradigm. It's also the reason
that string formatting exists at all.
To summarize:
// requires GC, too verbose, uses string composition which wastes
heap resources
writeln("The date is " ~ format("%04d", year));
// efficient, but format string and args can get out of sync.
writefln("the date is %04d", year);
//
writefln($"the date is {year:04d}");
If string interpolation gets reduced to the 2nd case, then it
will have the same efficiency and solve a problem. Whether that
problem justifies the change is up for debate, but I think it
*might be*.
More information about the Digitalmars-d
mailing list