Creating an array of immutable objects
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Feb 13 17:16:44 PST 2017
On 02/13/2017 04:59 PM, David Zhang wrote:
> 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.
I realize that I misunderstood you; see below for a mutable array.
The following code produces an immutable array through the use of the
misplaced std.exception.assumeUnique. (Why is it in std.exception? :) )
import std.stdio;
import std.algorithm;
import std.range;
string[] paths = [ "hello", "world" ];
struct FileDesc {
immutable string path;
immutable uint index;
}
immutable(FileDesc[]) _fileDesc;
FileDesc[] makeFileDescs(string[] paths) pure {
return paths.enumerate!uint.map!(t => FileDesc(t[1], t[0])).array;
}
static this() {
import std.exception : assumeUnique;
auto fd = makeFileDescs(paths);
_fileDesc = assumeUnique(fd);
}
void main() {
_fileDesc.each!writeln;
}
A mutable array is simpler:
import std.stdio;
import std.algorithm;
import std.range;
string[] paths = [ "hello", "world" ];
struct FileDesc {
immutable string path;
immutable uint index;
}
FileDesc[] _fileDesc;
FileDesc[] makeFileDescs(string[] paths) pure {
return paths.enumerate!uint.map!(t => FileDesc(t[1], t[0])).array;
}
static this() {
_fileDesc = makeFileDescs(paths);
}
void main() {
_fileDesc.each!writeln;
}
Ali
More information about the Digitalmars-d-learn
mailing list