In many modern languages const
correctness should be used to clarify interfaces and intent as well as to provide some opportunities to the compiler to optimize. In D there's the cool feature of really immutable data. How should const
and immutable
be used? I kinda figured, that preferring const
as qualifiers for functions arguments and immutable
for local variables seems to be a good way to write code, but as soon as you want to assign a struct with a reference or pointer like data member (private or not) to an immutable variable you can't do that.
struct S {
private int[] data;
}
void main() {
immutable s = new S; // won't work, since members aren't immutable
}
Hence, changing the implementation of a struct
can break my code, if I use immutable. Should I prefer const
for local variables and use immutable only when necessary? What are the guidelines?
You are extremely lucky - a video from DConf2013 with presentation devoted exactly to this topic has been published last week : http://youtu.be/mPr2UspS0fE
In your case, auto s = new immutable(S)();
should do the trick. You can then create data slice points to in constructor. However, if this slice may point to any data, then S can't possibly be immutable, because both const
and immutable
are transitive in D - they provide very strong guarantees not only about variable itself but also about any data that can be accessed from it indirectly via reference/pointer.
It is actually covered in linked video, but short summary is that you want to use immutable when really intend to. In other words, when you want your code to break if S
implementation changes so that immutable guarantees are no longer valid.