Associative Array c'tor

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 11 07:45:42 PDT 2016


On 07/11/2016 07:33 AM, Bahman Movaqar wrote:
 > On 07/11/2016 06:30 PM, Steven Schveighoffer wrote:
 >> Untested, but you could try MySt[][string].init.
 >
 > That did it.  Thanks.
 >
 >> But passing empty AA by value sometimes can be surprising. I'm not sure
 >> if it will work.
 >
 > Could you elaborate more?

Both AAs and slices behave like reference types even when passed by 
value: When a function adds an element, the argument sees that element 
as well. This is not the case when the argument is an empty (more 
correctly, null) AA or slice:

void foo(string[int] aa) {
     aa[1] = "one";
}

void main() {
     string[int] a;
     foo(a);
     assert(a is null);
     // The last result would be different if 'a' were not null
     // before calling 'foo'.

     string[int] b;
     b[0] = "zero";
     foo(b);
     assert(b[0] == "zero");
     assert(b[1] == "one");
}

Ali

P.S. There is std.array.assocArray if you already have a range of tuples 
at hand:

   https://dlang.org/phobos/std_array.html#.assocArray

P.P.S. There is std.algorithm.fold, which works with range chaining 
(unlike reduce, which was designed before ranges):

   https://dlang.org/phobos/std_algorithm_iteration.html#.fold



More information about the Digitalmars-d-learn mailing list