November 13, 2013 Re: Simple immutable example doesn't work - why??? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Louis Berube | On Wednesday, 13 November 2013 at 01:40:27 UTC, Louis Berube wrote:
> Does this correctly sum up what I have read? If so, this conversation has cleared up a great deal of my misunderstanding of how "immutable" works. It would be great to see the above examples in a D reference or tutorial (maybe the second edition of Andrei's book?).
Both yes and now. You are correct that those are two observable semantics but in practice it is the same immutability. I think it becomes easier to get when based on C foundation:
const char * s; // mutable pointer to constant elements"
char * const s; // constant pointer to mutable elements"
const char * const; // constant pointer to constant elements
In C "const" qualifier applies only to part of type it is qualified with.
In D, however, both "const" and "immutable" are transitive. That means that they do apply to type it is qualified with AND all stuff accessible from it. Without explicit brackets those apply to whole type:
immutable char * s; // immutable pointer, immutable elements
immutable(char*) s; // equivalent to (1)
immutable(char) * s; // mutable pointer, immutable elements
There is no such concept in D type system as "immutable pointer to mutable elements". So your two cases both use same "immutable", it is just applied to different parts of type.
It is all actually mentioned in TDPL as far as I can remember, but maybe relies too much on existing familiarity with transitivity concept.
|
November 13, 2013 Re: Simple immutable example doesn't work - why??? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Louis Berube | On Wednesday, 13 November 2013 at 01:40:27 UTC, Louis Berube wrote: > Thanks to both TFF and Kenji for their excellent explanations. I think my head is going to explode ;). > > So, as I understand it, there are two sorts of immutable entities in D. > > The first is probably the one most familiar to the majority of us, which is an entity with immutable contents but with mutable binding. This is what TFF illustrated so well in his post above and what we are all familiar with as "string". > > The second will take me longer to get used to, which is an entity with immutable contents *and* with immutable binding. This is what I tripped over in my example and what Kenji adroitly showed how to deal with in his post. > > Does this correctly sum up what I have read? If so, this conversation has cleared up a great deal of my misunderstanding of how "immutable" works. It would be great to see the above examples in a D reference or tutorial (maybe the second edition of Andrei's book?). > > Many thanks. There's a Rebindable template in Phobos which I think does what you want: http://dlang.org/phobos/std_typecons.html#.Rebindable |
Copyright © 1999-2021 by the D Language Foundation