Assoc. Array and struct with immutable member

bauss jj_1337 at live.dk
Tue Apr 17 11:07:55 UTC 2018


On Sunday, 15 April 2018 at 18:51:52 UTC, Alex wrote:
> On Sunday, 15 April 2018 at 17:59:01 UTC, Dgame wrote:
>> How am I supposed to insert a struct with immutable members 
>> into an assoc. array?
>>
>> Reduced example:
>> ----
>> struct A {
>>     immutable string name;
>> }
>>
>> A[string] as;
>> as["a"] = A("a"); // Does not work
>> ----
>
> Via a static this() it would work. But I guess, this is not 
> what you are looking for, is it?
>
> ´´´
> static this()
> {
> 	as["a"] = A("a");
> }
>
> void main()
> {	
> 	assert(as["a"].name == "a");
> }
>
>
> struct A {
>     immutable string name;
> }
>
> A[string] as;
> ´´´
>
>
> It also works, if you hide the AA in a class and all the 
> insertions into the constructor.
>
>
> ´´´
> /*
> static this()
> {
> 	as["a"] = A("a");
> }
> */
> void main()
> {	
> 	auto c = new Container(A("a"));
> 	assert(c.as["a"].name == "a");
> }
>
> struct A {
>     immutable string name;
> }
>
> class Container
> {
> 	A[string] as;
> 	this(A a)
> 	{
> 		as[a.name] = a;
> 	}
> }
> ´´´

Even though it works in static this, then it still looks like a 
bug if you ask me, because the associative array itself isn't 
immutable.


More information about the Digitalmars-d-learn mailing list