Search code examples
arrayssyntaxdimmutabilityimmutablearray

Mutable array of immutable length in D


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);
}

Solution

  • 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