Creating an array of immutable objects

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Feb 14 23:35:16 PST 2017


On 2017-02-15 01:08, David Zhang wrote:
> Thanks for your answers. Out of curiosity though, how could something
> like this be done with classes instead?

You mean if FileDesc was a class? It's basically the same. You would need:

Mutable array:

1. Add a constructor which sets all immutable instance variables

For immutable array:

0. Same as above
1. The constructor needs to be declared as "immutable"
2. The instances need to be created with "immutable new"

In the example below, there are two constructors, one for creating 
mutable instances and one for immutable instances. This is only needed 
since I'm creating both a mutable and an immutable array with the same 
type. You only need one kind of constructor if you only need a mutable 
or an immutable array.

module main;

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

class FileDesc {
     immutable string path;
     immutable uint index;

     this(string path, uint index) immutable
     {
         this.path = path;
         this.index = index;
     }

     this(string path, uint index)
     {
         this.path = path;
         this.index = index;
     }
}

// immutable array created at compile time
immutable _fileDesc = paths
     .enumerate!uint
     .map!(t => new immutable FileDesc(t.value, t.index))
     .array;

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

auto makeFileDescs(const string[] paths)
{
     return paths.enumerate!uint.map!(t => new 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