Add to a List in D

jessekphillips

Jesse Phillips

Posted on August 23, 2019

Add to a List in D

I thought this would be easy, considering I couldn't even provide a boolean it should be a surprise. D is understandably a different story. D provides array and associative arrays. These are generally sufficient and reaching for a container library isn't necessary.

Arrays utilize [] to denote the type and create literals.

string[] arrayVarName;
arrayVarName = ["array literal value"];
Enter fullscreen mode Exit fullscreen mode

Unlike every other language, D does not use addition to indicate concatenation.

arrayVarName ~= "additional value";
Enter fullscreen mode Exit fullscreen mode

This is often referred to as the append operator because arrays have reserved space where this might not cause an allocation.

This also works with array.

arrayVarName ~= ["more", "values"];
Enter fullscreen mode Exit fullscreen mode

Two lists can be combined with concatenation.

arrayVarName = ["value"] ~ ["more", "values"];
Enter fullscreen mode Exit fullscreen mode

And since D has operator overloading, user types these can have appropriately defined behavior on class or struct. Again this uses D powerful templates and is beyond this tutorial.

https://stackoverflow.com/questions/7826891/elegant-operator-overloading-in-d

💖 💪 🙅 🚩
jessekphillips
Jesse Phillips

Posted on August 23, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Memory Free Programming in D
dlang Memory Free Programming in D

February 11, 2020

Regular Expressions in D
regex Regular Expressions in D

December 30, 2019

Printing in D
dlang Printing in D

December 15, 2019

List Comprehension in D
dlang List Comprehension in D

December 13, 2019

Compile-Time Reflection
dlang Compile-Time Reflection

December 9, 2019