为什么筛选字符串列表会在此处导致错误

Why filter for a list of strings is causing error here

我正在尝试使用以下代码过滤字符串列表以仅获取长度大于 1 的字符串:

import std.stdio;
import std.string;
import std.algorithm;

void main(){
    auto slist = ["a","aa","b","bb","c","cc","dd",]; 
    slist = slist.filter!(a => a.length>1);     // does not work; 
    writeln(slist); 
}

但是,它正在创建错误:

$ rdmd soq_map_filter_strlist.d
soq_map_filter_strlist.d(7): Error: cannot implicitly convert expression filter(slist) of type FilterResult!(__lambda1, string[]) to string[]
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_map_filter_strlist.d", "-I."]

问题出在哪里,如何解决?感谢您的帮助。

filter returns 惰性范围,无法隐式转换回 string[]。您可以将它分配给一个新变量,或者使用 std.array.array:

将其评估为一个数组
slist = slist.filter!(a => a.length>1).array;
writeln(slist);

— 或 —

auto slist2 = slist.filter!(a => a.length>1);
writeln(slist2);