On Monday, 27 December 2021 at 19:38:38 UTC, frame wrote:
> I feel stupid right now: One cannot assign a struct that contains const member to AA?
Error: cannot modify struct instance ... of type ... because it contains const
or immutable
members
This is considered a modification?
struct S
{
const(int) a;
}
S[string] test;
test["a"] = S(1);
Whats the workaround for that?
const/immutable members are to be set/assigned instantiation. Most likely the problem is a bug and sounds like
a) the struct doesn't exist in the AA, so it creates it (with a default)
b) It tries to copy but contains a const and thus fails
Passing a pointer will do you no good, since structs are likely to be on the stack.
So let's try opAssign.
auto ref opAssign(S s) {
this=s;
return this;
}
So we get
'cannot modify struct instance `this` of type `S` because it contains `const` or `immutable` members'.
Alright let's look at the members we can work with.
https://dlang.org/spec/hash-map.html
I don't see an 'add' but i do see a 'require' which will add something in. So we try that.
test.require("a", S(1));
Now we get:
Error: cannot modify struct instance `*p` of type `S` because it contains `const` or `immutable` members
test.d(??): Error: template instance `object.require!(string, S)` error instantiating
Hmmm it really doesn't like it. Finally we can fake it. Let's make a mirror struct without the const, for the purposes of adding it.
struct S
{
const(int) a;
}
struct S2
{
int a;
}
S[string] test;
cast(S2[string])test = S2(1);
Error: `cast(S2[string])test` is not an lvalue and cannot be modified
Well that's not going to work. Let's make it a pointer and allocate it instead.
S*[string] test;
test["a"] = new S(1);
Success!
So i summarize, either work with a pointer, or drop the const...