2

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);
}
Jeroen
  • 15,257
  • 12
  • 59
  • 102

2 Answers2

4

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
Adam D. Ruppe
  • 25,382
  • 4
  • 41
  • 60
2

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
}
Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114