[Issue 8008] static array literal syntax request: auto x=[1,2,3]S;

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sat Dec 27 05:22:24 PST 2014


https://issues.dlang.org/show_bug.cgi?id=8008

--- Comment #7 from bearophile_hugs at eml.cc ---
If you want to generate certain i,i+10 pairs you can use this, but it generates
lot of not efficient allocations:

void main() @nogc {
    import std.range: iota;
    import std.algorithm: map;
    auto pairs = 10.iota.map!(i => [i, i + 10]);
    foreach (p; pairs) {} // Isn't @nogc.
}


You can solve it using a little wrapper struct, but the result isn't an array
despite the alias this:

void main() @nogc {
    import std.range: iota;
    import std.algorithm: map;
    static struct Pair { int[2] a; alias a this; }
    auto pairs = 10.iota.map!(i => Pair([i, i + 10]));
    foreach (p; pairs) {} // OK
}


You can also use this, but casts are unsafe things and it's better to minimize
their usage:

void main() @nogc {
    import std.range: iota;
    import std.algorithm: map;
    auto pairs = 10.iota.map!(i => cast(int[2])[i, i + 10]);
    foreach (p; pairs) {} // OK
}


the []s syntax is handy to solve the problem, avoiding to create and manage a
new type and keeping all safety:

void main() @nogc {
    import std.range: iota;
    import std.algorithm: map;
    auto pairs = 10.iota.map!(i => [i, i + 10]s);
    foreach (p; pairs) {} // OK
}

--


More information about the Digitalmars-d-bugs mailing list