What type of `print` formatting do you prefer?

rempas rempas at tutanota.com
Tue Dec 21 17:29:34 UTC 2021

On Tuesday, 21 December 2021 at 11:17:47 UTC, bauss wrote:
> Personally I prefer the C# way where it's explicit what "index" 
> the argument comes from:
> ```d
> print("My name is {0}! Nice to meet you!\n", "Maria");
> // C# doesn't have a binary format, but does hex
> // However due to being explicit about the index we can remove 
> the second argument for the formatting.
> print("I am {0} years old! And in hex, that is: 0x{0:X}\n", 19);
> ```

That's actually awesome and Rust supports this too! However, this 
will makes things even more complicated and less readable. It 
will also make the parser slower and it will require more code to 
implement (and more code = more chances to create bugs especially 
for inexperienced programmers like me). However, other than been 
good on the eyes, this can also be very useful in some cases 
(that will be rare tho). Let's consider the following example:

print("My name is {} and my mother's name is also {} and my 
father is called {}\n", "Maria", "Maria", "Steve");

In this case we are using the string "Maria" twice which is both 
inefficient and silly (and the design is bad in general). So in 
this case the following will be better:

print("My name is {} and my mother's name is also {0} and my 
father is called {}\n", "Maria", "Steve");

We will call this positional placeholders. Now watch carefully 
the behavior. The first placeholder will get the first ("Maria") 
value then the current argument will be the second one ("Steve") 
for the next placeholder that will be used. However, positional 
placeholders can use any argument they want (in debug mode there 
will also be boundschecking) and they won't use and change the 
current argument so the third placeholder will use the second 
argument automatically. You can think of positional placeholders 
as they are "skipping" the current argument (and choose whatever 
they want) and pass their turn to the next one.

Like I said, this will rarely be useful but I still want to 
implement them and this behavior is the best I could think that 
will also not be super complicated to implement and use. Also to 
me the cases were this will be needed, there won't be a need for 
special formatting so the default automatic formatting will be 
enough. Keep in mind that my approach of doing things is to 
implement only the absolutely (well maybe a little bit more in 
some cases) necessary. Fully featured but not complicated if you 
get me.

More information about the Digitalmars-d mailing list