Search code examples
arraysddynamic-arraysstatic-array

Function that accepts static arrays of any size (D)


How do I create a function that supports static arrays of any size?

Something like:

@safe pure nothrow void fillArray(ref ubyte[] array) {
    /**
     * How do I make this function support arrays of any
     * size; but they don't have to be dynamic?
    **/
}

Solution

  • What you need to do is remove the ref from your argument. When you use reference, it means that when you resize the array inside the function, it'll also be resized outside the function, which obviously isn't possible with static arrays.

    When you do not use ref, you can still edit the array contents. When you resize the array however, only the local copy of the array pointer will get updated with the new length. The local copy will have a different size; the original pointer will still have it's original size.

    If you sliced the array, it'd work too, because the reference the function got would be a new made reference to that slice of the array anyway; it would not equal the original reference.