I'm searching for a way to do something like this in D:
struct MyStruct {
const size_t length;
int *const data;
MyStruct(size_t n) : length(n) {
data = new int[length];
}
}
This way it is mutable, but non resizeable:
MyStruct s = MyStruct(10);
s.data[0] = 42; // Valid
s.data = new int[20]; // Error: assignment to const
Doing some extra reading about the theme I found the section on Type Qualifiers, which makes me believe that the "tail constness" of D will disallow this kind of behavior.
My solution would be overriding the []
to make MyStruct behave as an array and hiding the implementation details, but if you have a more elegant solution I'm all ears!