Is it possible in D to have a mutable array of which the length is not known at compile time to have a static length?
void testf(size_t size) {
int immutable([]) testv = new int[](a);
}
Is it possible in D to have a mutable array of which the length is not known at compile time to have a static length?
void testf(size_t size) {
int immutable([]) testv = new int[](a);
}
You can wrap the native array type in a custom type which restricts access to the length
property:
struct FixedLengthArray(T)
{
T[] arr;
alias arr this;
this(size_t size) { arr = new T[size]; }
@property size_t length() { return arr.length; }
}
void main()
{
auto arr = FixedLengthArray!int(10);
arr[1] = 1; // OK
arr[2..4] = 5; // OK
assert(arr.length == 10); // OK
arr.length = 12; // Error
}
Nope, at least not unless you provide your own array wrapper. You could do something like:
Notice the disabled length setter and append operator which pretty much implements what you want.