Assoc. Array and struct with immutable member

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Apr 17 11:38:17 UTC 2018


On Sunday, April 15, 2018 17:59:01 Dgame via Digitalmars-d-learn 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
> ----

I would point out that in general, having const or immutable fields in a
struct is a terrible idea. It causes all kinds of problems because stuff
like assignment doesn't work. If you want the field to be read-only, you'll
have far fewer problems if you simply use a function to access it instead of
making the member public. e.g.

struct A
{
public:

    @property string name() { return _name; }

private:

    string _name;
}

The problem you're having here is just one example of the list of things
that don't work if you have a struct with immutable members. It looks like
the AA probably is doing something like initializing the entry with A.init
and then assigning it the new value, and that's not going to work if the
struct has immutable members - which is exactly what the error message says.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list