Class qualifier vs struct qualifier

RazvanN razvan.nitu1305 at gmail.com
Thu Jun 14 08:39:48 UTC 2018


> Honestly, from what I understand of how this works, what I find 
> weird is the struct case. immutable on classes does _not_ make 
> the class itself immutable. It just makes all of its members 
> immutable - hence the error about trying to allocate new Foo 
> instead of new immutable Foo. So, that is exactly what I would 
> expect. And honestly, being able to write Foo and have it imply 
> immutable Foo would get _really_ confusing when reading and 
> debugging code.

Maybe it has something to do with structs being value types and 
classes
being reference types. If you declare an immutable struct then 
you cannot
modify it's value, while if you declare a class, the pointer to 
the class
is mutable, while the class fields are not. This kind of makes 
sense, however
the thing is that in both situations you are not able to mutate 
any of the
class/struct fields no matter how you instantiate it, so it is 
really redundant
to use `immutable` when creating the instance.

> What's bizarre is that marking the struct with immutable would 
> affect anything other than its members.
>
> Bar b;
>
> should not claim that typeof(b) is immutable(Bar). b was not 
> marked as
> immutable. It was listed as Bar, not immutable Bar. So, b 
> shouldn't be
> immutable.
>
> - Jonathan M Davis




More information about the Digitalmars-d-learn mailing list