简体   繁体   English

如何为迭代器创建 rust 过滤谓词?

[英]How to create a rust filter predicate for an iterator?

pub struct S{
    a: u32
}
fn main() {
    let ve = vec![S{a: 1}, S{a: 2}];
    ve.iter().filter(filter_function);
}

fn filter_function(s: &S) -> bool {
    todo!()
}

Gives

error[E0631]: type mismatch in function arguments
   --> src/main.rs:6:22
    |
6   |     ve.iter().filter(filter_function);
    |               ------ ^^^^^^^^^^^^^^^ expected signature of `for<'r> fn(&'r &S) -> _`
    |               |
    |               required by a bound introduced by this call
...
9   | fn filter_function(s: &S) -> bool {
    | --------------------------------- found signature of `for<'r> fn(&'r S) -> _`
    |
note: required by a bound in `filter`

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=caf542348c2b744abace8e7b6b30d766 https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=caf542348c2b744abace8e7b6b30d766

And I have no idea why.我不知道为什么。 The signatures are the same.签名是一样的。 What is wrong?怎么了?

The signatures aren't quite the same.签名不太一样。 The expected type is a function which takes a &'r &S , while your function takes a &'r S .预期的类型是 function ,它采用&'r &S ,而您的 function 采用&'r S One has an extra layer of indirection.一个有一个额外的间接层。

You need a function that takes a double reference and calls filter_function with a single reference.您需要一个 function 采用双引用并使用单引用调用filter_function We can do that with an explicit dereference.我们可以通过显式取消引用来做到这一点。

ve.iter().filter(|x| filter_function(*x));

However, generally, Rust is pretty good at sorting out these kinds of dereferencing problems in lambdas, so we can simply write不过,一般来说,Rust 对 lambda 中这类解引用问题的梳理还是不错的,所以我们可以简单地写

ve.iter().filter(|x| filter_function(x));

and Rust is smart enough to handle the double reference for us. Rust 足够聪明,可以为我们处理双重参考。

It's worth mentioning that there should be no performance hit for the extra lambda.值得一提的是,额外的 lambda 应该不会影响性能。 filter takes a generic argument, which means it'll be statically dispatched and hence will be very easy for an optimizer to inline. filter采用通用参数,这意味着它将被静态分派,因此优化器很容易内联。 So the performance should be equivalent to having a top-level function.所以性能应该相当于拥有一个顶级的function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM