Code similar to this is not uncommon. Currently it's refused:


immutable data = [1, 5, 3, 1, 5, 1, 5];
void main() @nogc {
    import std.algorithm: count;
    assert(data.count([1, 5]) == 3);
}


test.d(4,23): Error: array literal in @nogc function main may cause GC allocation


The current workaround is not handy when you have conditionals, etc:

immutable data = [1, 5, 3, 1, 5, 1, 5];
void main() @nogc {
    import std.algorithm: count;
    immutable static part = [1, 5];
    assert(data.count(part) == 3);
}


A language solution is a literal syntax for fixed-sized arrays (here I slice it again because unfortunately count doesn't accept fixed-sized arrays):


immutable data = [1, 5, 3, 1, 5, 1, 5];
void main() @nogc {
    import std.algorithm: count;
    assert(data.count([1, 5]s[]) == 3);
}


I remember Kenji is not fond of this []s syntax, for reasons I don't remember. Do you think there are other better/different solutions?

Bye,
bearophile

Reply via email to