On Thursday, 5 September 2019 at 15:48:40 UTC, Ali Çehreli wrote:
That's the misunderstanding: The existing object is assigned over. The address is the same:

void main() {
  int[int] aa;
  aa[1] = 1;
  const oldPointer = (1 in aa);
  aa[1] = 11;
  assert(oldPointer is (1 in aa));  // Passes
}

First, I thought, I've got understood it now, but then I wrote this little program and the result was not, what I thought it would be:

void main()
{
    int[int] a;

    immutable int b = 17;
a[1] = b; // <-- expecting error here
    const oldPointer = (1 in a);
    immutable int c = 10;
    a[1] = c;
    assert(oldPointer is (1 in a));

    Point[int] d;

    immutable Point e = Point(17);
    d[1] = e;                           // <-- but error is here
}

struct Point
{
    immutable int x;
}

What's the difference? I can put an immutable int in an AA and I can overwrite it (pointer is still the same), but I can't do that with a struct, having an immutable member. When I remove that immutable inside of the struct it works. ?!?

While writing this, I had an other idea, namely, that changing d[1] would make e to be something different (x inside Point is mutable this time):

Point e = Point(17);
d[1] = e;
d[1] = Point(19);
writeln(e);

But it's still 17.


const or immutable members make structs unassignable.

But why? Here:

Point[3] f;
f[0] = Point(3);

I understand, that I cannot change f[0], because it's allready got a default value and that value would be overwritten. But in an aa, that member does not exist before putting the Point in there, hence there is nothing, that could be overwritten...

Whether the members of a type are const or immutable should not be dictated by where the objects of that type will be used. If it makes sense otherwise, sure...

I'm not sure if I understand that right. It's sort of an advice on how to decide if one want's to make a member immutable or not, is it?

If you are worried about existing elements being modified, you can provide a different container that wraps an AA, but provides an opIndex that returns 'ref const(T)'. That would solve the immutability of the elements in the container.

No, I don't worry about such things. My program runs smoothly when I don't make that members immutable. And I could perfectly live with that But that's the maxim I used the last three years: "If avoidable, don't use 'immutable' at all, it only causes problems." But that is not satisfiable. Because if immutable were that useless, why would it exist at all? So I would like to understand, what's happening; being able to predict, what works and what not. At the moment it's almost always the opposite of what I think it should be...

Reply via email to