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

时间:2019-06-13 12:16:52

标签: filter d

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

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."]

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

1 个答案:

答案 0 :(得分:2)

filter返回一个惰性范围,该范围不能隐式转换回string[]。您既可以将其分配给新变量,也可以使用std.array.array对其进行求值:

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

—或—

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