Create an array with immutable elements
Jonathan M Davis
jmdavisProg at gmx.com
Thu Jun 14 17:18:12 PDT 2012
On Friday, June 15, 2012 01:57:35 Roman D. Boiko wrote:
> immutable struct Node{ string s; }
> Node[] f()
> {
> Node[] arr = ...?
> return arr;
> }
>
> How to fill an array, if its elements are immutable? I want to
> assign values calculated by some function.
There are 3 options that I know of:
1. Create an empty array and append the elements to it.
2. Use Appender (which will be more efficient than #1). e.g.
auto app = appender!(immutable Node[])();
app.put(value1);
app.put(value2);
//...
auto arr = app.data;
3. Create the array as mutable and then cast it to immutable.
auto arr = new Node[](length);
arr[0] = value1;
arr[1] = value2;
//..
auto immArr = cast(immutable(Node)[])arr;
or better
auto immArr = assumeUnique(arr);
though that will make the whole array immutable rather than just the Nodes -
though that can be fixed by doing
auto immArr = assumeUnique(arr)[];
since array slices are tail-const.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list