Creating an array of immutable objects

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 14 01:49:57 PST 2017


On 2017-02-14 01:59, David Zhang wrote:
> Hi,
>
> I have a struct with two immutable members, and I want to make an array
> of them. How do I to this? I'm using allocators for this.
>
> string[] paths;
>
> struct FileDesc {
>     immutable string path;
>     immutable uint index;
> }
>
> _fileDesc = /*something*/;
>
> You can't use alloc.makeArray because it requires a range with which to
> initialize the array, and while I can produce an array of paths, I don't
> know how to merge both a range of paths and indices. Lockstep doesn't work.
>
> I also tried using emplace and an allocated byte array, but it gave me
> random values and was (I think) unnecessarily complicated. What am I
> missing?

Here are two examples, one creating an immutable array at compile time. 
The other one creating a mutable array at application startup using 
allocators:

import std.algorithm;
import std.range;

immutable string[] paths = [ "hello", "world" ];

struct FileDesc {
     immutable string path;
     immutable uint index;
}

// immutable array created at compile time
immutable _fileDesc = makeFileDescs(paths).array;

// mutable array created at application start using allocators
FileDesc[] _fileDesc2;

auto makeFileDescs(const string[] paths)
{
     return paths.enumerate!uint.map!(t => FileDesc(t.value, t.index));
}

static this()
{
     import std.experimental.allocator;
     _fileDesc2 = theAllocator.makeArray!FileDesc(makeFileDescs(paths));
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list