Mixing std.container.array and Appender

axricard axelrwiko at gmail.com
Mon Feb 9 08:37:25 UTC 2026


On Saturday, 7 February 2026 at 04:31:33 UTC, IchorDev wrote:
> On Wednesday, 4 February 2026 at 08:45:06 UTC, axricard wrote:
>> Hello, is there some structure in standard library that acts 
>> like Appender but works also on std.container.array Arrays ?
>> I'd like to have the capacity of Arrays doubling every time 
>> new memory is allocated.
>> Appender requires the input to be a dynamic array, which is 
>> not the case for std.container.array Arrays.
>
> `Appender` only exists so that you can continually append to a 
> dynamic array without the GC having to look up its `capacity` 
> for every append. `Array` already keeps track of its own 
> [`capacity`](https://dlang.org/phobos/std_container_array.html#.Array.capacity), so you don't need to use an `Appender` on it, just use `Array` on its own.

I see your point, but my question was more about an other nice 
property of Appender's: they double their size every time they 
need to re-allocate, which is not the case in for std.container 
Arrays. Do I have to write my own wrapper to have such behavior 
with Array's ?



```D
import std;

void append(T)(ref T arr, int elem)
{
     arr ~= elem;
     writefln("capacity after append: %u", arr.capacity);
}

void main()
{
     writeln("Appender");
	auto app = appender!(int[])();
     foreach(i; iota(0, 20))
    		app.append(i);

     writeln("\n=============");
     writeln("Array");
	auto arr = Array!(int)();
     foreach(i; iota(0, 20))
    		arr.append(i);
}
```

Output:
```
Appender
capacity after append: 8
capacity after append: 8
capacity after append: 8
capacity after append: 8
capacity after append: 8
capacity after append: 8
capacity after append: 8
capacity after append: 8
capacity after append: 16
capacity after append: 16
capacity after append: 16
capacity after append: 16
capacity after append: 16
capacity after append: 16
capacity after append: 16
capacity after append: 16
capacity after append: 32
capacity after append: 32
capacity after append: 32
capacity after append: 32

=============
Array
capacity after append: 1
capacity after append: 2
capacity after append: 4
capacity after append: 4
capacity after append: 7
capacity after append: 7
capacity after append: 7
capacity after append: 11
capacity after append: 11
capacity after append: 11
capacity after append: 11
capacity after append: 17
capacity after append: 17
capacity after append: 17
capacity after append: 17
capacity after append: 17
capacity after append: 17
capacity after append: 26
capacity after append: 26
capacity after append: 26
```


More information about the Digitalmars-d-learn mailing list