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);
}
Nope, at least not unless you provide your own array wrapper. You could do something like:
struct ImmutableLength {
int[] array;
alias array this; // allow implicit conversion to plain array
this(int[] a) { array = a; } // initialization from plain array
@property size_t length() { return array.length; }
@disable @property void length(size_t) {}
@disable void opOpAssign(string op: "~", T)(T t) {}
@disable void opAssign(int[]) {}
}
Notice the disabled length setter and append operator which pretty much implements what you want.
auto i = ImmutableLength([1,2,3]); // declare it like this
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
}