DEV Community

Jesse Phillips
Jesse Phillips

Posted on

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

Top comments (0)