why use string for this example of appender?

WhatMeForget kheaser at gmail.com
Mon Apr 16 06:46:36 UTC 2018


I think I got a handle on D's static and dynamic arrays, till I 
come to std.array and see all the shiny new tools. I can 
understand all the replace.. functions, but the appender function 
gave me pause. The documentation says appender "Returns a new 
Appender or RefAppender initialized with a given array."

My first thought that doesn't D's built in arrays already allow 
appending? (at least for dynamic arrays)  And the example shows 
the use of appender with string.  Isn't string an immutable array 
or characters?  Wouldn't this be the last data type you would 
want to be appending to?  Another thing that had me wondering is 
the use of put() down below; doesn't the append syntax (~=) give 
you the same exact functionality; so why bother?

void main()
{
     import std.array;
     import std.stdio: write, writeln, writef, writefln;
     auto w = appender!string;
     // pre-allocate space (this avoids costly reallocations)
     w.reserve(10);
     assert(w.capacity >= 10);

     w.put('a'); // single elements
     w.put("bc"); // multiple elements

     // use the append syntax
     w ~= 'd';
     w ~= "ef";

     writeln(w.data); // "abcdef"


More information about the Digitalmars-d-learn mailing list