On Friday, 15 June 2012 at 00:18:23 UTC, Jonathan M Davis wrote:
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
Please note that type of Node is immutable. So the third option
is disallowed. But I got enough answers, thanks to everybody!