Assoc. Array and struct with immutable member
Alex
sascha.orlov at gmail.com
Sun Apr 15 18:51:52 UTC 2018
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;
}
}
´´´
More information about the Digitalmars-d-learn
mailing list