Interpolated strings

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Tue Apr 18 15:20:15 PDT 2017


On Tue, Apr 18, 2017 at 09:56:28PM +0000, Jonathan Marler via Digitalmars-d wrote:
[...]
> I've thought about it and decided, I like this idea.  I've only used
> interpolated strings in PHP which left a bad taste, but I realized
> that interpolating strings makes it impossible for your format string
> and your arguments to get out of sync. This makes interpolated strings
> harder to use incorrectly (Scott Meyers had a good talk on this,
> https://www.youtube.com/watch?v=5tg1ONG18H8).
[...]

Phobos git HEAD now supports compile-time format strings of the form:

	writefln!"My %s value is %d."("field", 123);

If your arguments are out of sync with the format string, this will
abort with a compilation error. So you won't end up in the situation
where the format string or arguments are wrong but you only find out
when it throws a runtime exception. Or worse, in the C situation where
mismatched format string / arguments can lead to stack overruns and
security exploits. (Though C compilers have been hacked to check this
and issue warnings. But that's veering offtopic.)

Having said that, though, there is still one problem where you can still
get into trouble:

	writefln!"The date is %04d-%02d-%02d"(month, year, day);

It may not be immediately obvious that month and year have been
transposed (presumably by mistake), because the %d specifier happens to
work with both argument orderings. Whereas in an interpolated string, it
becomes painfully obvious:

	// Using OP's tentative proposed syntax
	writeln($"The date is {month}-{year}-{day}");
	//                    ^^^^^^^^^^^^^^ mistake is obvious here

This problem may be especially prominent in D because we're used to
writing %s as a general specifier that works for any argument type.


T

-- 
Long, long ago, the ancient Chinese invented a device that lets them see
through walls. It was called the "window".


More information about the Digitalmars-d mailing list