R..
R..

Reputation: 123

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?

Upvotes: 1

Views: 81

Answers (2)

dmakarov
dmakarov

Reputation: 81

MySlice[] is an array of string[int], i.e. each element of the variable 'list' is string[int]. If that's what you want, then the code should be something like

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

The result will be

[[0:"zero", 1:"one", 2:"two", 3:"three", 4:"four"], [0:"zero", 1:"one", 2:"two"]]

If you want to join two arrays slice1 and slice2 in a single string[int] array, you need to iterate over each array and copy elements into list

alias MySlice = string[int];
MySlice list;
foreach (k, v; slice1)
  list[k] = v;
foreach (k, v; slice2)
  list[k] = v;
writeln(list);

And the result will be

[0:"zero", 4:"four", 1:"one", 2:"two", 3:"three"]

Upvotes: 4

Marc Schütz
Marc Schütz

Reputation: 1061

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;

Upvotes: 4

Related Questions