Search code examples
arraysd

Using .length returns incorrect number of elements


When using the .length property of a dynamic array why does it return the incorrect number of elements after I use the appender?

If I use the ~= syntax it returns the correct length.

Code:

import std.stdio;
import std.array : appender;

void main()
{
    //declaring a dynamic array
    int [] arrayofNumbers;
    //append an element using the ~= syntax
    arrayofNumbers ~= 1;
    arrayofNumbers ~= 2;
    //print the array
    writeln(arrayofNumbers);

    //Using appender
    auto appendNumber = appender(arrayofNumbers);
    appendNumber.put(10);
    writeln(appendNumber.data);

    writeln(arrayofNumbers.length);

}

I was reading this article, and I think the relevant portion states:

Another consequence of this is that the length is not an array property, it's a slice property. This means the length field is not necessarily the length of the array, it's the length of the slice. This can be confusing to newcomers to the language.

However that is referring to slices and dynamic arrays.


Solution

  • According to the documentation appender.data returns a managed array. So the correct way to get the number of elements is to call .length on the returned array.

    Corrected Code:

    int [] managedArray = appendNumber.data;
    writeln(managedArray.length);
    

    or

    writeln(appendNumber.data.length);