![](/img/trans.png)
[英]Is it possible to use Iterator::filter_map to add conditional filtering?
[英]How to specify type information for Iterator::filter_map?
fn main() {
let a = ["1", "2", "lol"];
let cnt = a.iter().filter_map(|s| s.parse().ok()).count();
}
错误信息
<anon>:3:24: 3:34 error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [E0282]
<anon>:3 let cnt = a.iter().filter_map(|s| s.parse().ok()).count();
^~~~~~~~~~
我尝试为filter_map()
指定类型, filter_map()
成功。 如果可能的话,我也想知道为什么如果删除count()
方法,编译器不会抱怨。
编译器不知道解析的结果类型,因为编写代码的方式对任何类型都适用。 您需要特别注释此方法调用: s.parse::<i32>().ok()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.