Immutable struct with AA init problem

Ali Çehreli acehreli at yahoo.com
Tue Nov 26 08:46:27 PST 2013


On 11/26/2013 02:12 AM, Uranuz wrote:> As far as I understand in current 
implementation of Dlang it's not
 > possible to write:
 >
 > immutable(EnumFormat) magicCreatures =
 > immutable(EnumFormat)([1:"goblin", 2:"ork", 3:"elf", 7:"dwarf"], false);

It is a shame that either the design and implementation of const, 
immutable, construction, associative arrays, etc. or our understanding 
of such complexities are still incomplete but at least what you show 
works as long as there is an immutable constructor.

The following main constructs one mutable and one immutable object:

struct S
{
     string[int] aa;
     bool b;

     this(string[int] aa, bool b)
     {
         this.aa = aa;
         this.b = b;
     }

     this(immutable(string[int]) aa, bool b) immutable
     {
         this.aa = aa;
         this.b = b;
     }
}

void main()
{
     auto sm = S([1:"mut"], false);
     auto si = immutable(S)([2:"imm"], true);
}

 > It's because AA literal isn't immutable.

Actually, AA literals can be used to initialize an immutable AA as well:

     immutable(string[int]) aaimm = [ 1 : "aa imm" ];

 > But is there some method similar to assumeUnique() for AA? Using static
 > this() to define some constants looks awkward as I believe.

assumeUnique works with AAs as well:

import std.exception;

void main()
{
     auto aa = [ 1 : "one" ];
     static assert(is (typeof(aa) == string[int]));

     auto aaimm = assumeUnique(aa);
     static assert(is (typeof(aaimm) == immutable(string[int])));
}

Ali



More information about the Digitalmars-d-learn mailing list