DIP 1027---String Interpolation---Community Review Round 1

mipri mipri at minimaltype.com
Mon Dec 16 22:48:30 UTC 2019

On Monday, 16 December 2019 at 22:12:37 UTC, mipri wrote:
> but this
> would all be a distraction from explaining why D's string
> interpolation is different.

Here's some prose that I'd expect in a FAQ or tutorial.

* What do you mean, "it doesn't build strings"!?

i"$a $b $c" is translated to an argument list

   "%s %s %s", a, b, c

So it has no meaning outside of argument-passing.

* Why do that? No other language does that!

Those other languages also have some severe problems owing to
how they do string interpolation:

1. a universe of SQL injection and similar exploits, as it's
easy and convenient to build strings with interpolation even
though the underlying database APIs can accept arguments
separately and safely, with no need for ad-hoc 'sanitization'.

Well-written database code in these languages is therefore
written as if string interpolation is not a feature of the

   $db->query("INSERT INTO names VALUES (?)", "Bob");

2. internationalization is defeated, as the structure of the
string that variables are interpolated into is lost. Invariably
as programs get international their developers have to comb
through the code base and remove uses of string interpolation:

   print("Hello, $name!");

   # is corrected to:

   printf(gettext("Hello, %s!"), name);

where gettext() might look up "Hello, %s" in a
translator-maintained table of greetings, to substitute
"Bonjour, %s".

In D, string interpolation is convenient for the simplest
tasks, and D is unusual in that string interpolation *remains*
convenient as tasks get more serious.

This comes at the small cost of having to pass an interpolated
string to a string-building function, like std.format's format,
if that's what you want.

   string s1 = i"Hello, $name!"; // error

   string s2 = i"Hello, $name!".format; // this is fine

   string s3 = format("Hello, %s!", name); // without i""

Even if the intended purpose is working with C-style printf()
functions, I'd highlight this use of i"" in a C interface or
BetterC section.

More information about the Digitalmars-d mailing list