Search code examples
arraysmultidimensional-arrayd

Array of Key->Value array


I am starting with the D language (D2) and I am trying to do the following:

string[int] slice1 = [ 0:"zero", 1:"one", 2:"two", 3:"three", 4:"four" ];
string[int] slice2 = [ 0:"zero", 1:"one", 2:"two"];

alias MySlice = string[int];
MySlice[] list;
list[] =slice1;
list[]=slice2;
writeln(list);

It compiles but the list stays empty. What did I miss?


Solution

  • list[] = slice1;

    I guess you're expecting this to append slice1 to the list, as in PHP. But the meaning in D is: "Assign slice1 to each of the elements in the list." As your list has no elements, nothing is being changed.

    For appending, use the ~= operator:

    list ~= slice1;