迭代器方法take_while
将一个闭包作为其参数。
例如:
fn main() {
let s = "hello!";
let iter = s.chars();
let s2 = iter.take_while(|x| *x != 'o').collect::<String>();
// ^^^^^^^^^^^^^
// closure
println!("{}", s2); // hell
}
这对于简单的闭包很好,但是如果我想要一个更复杂的谓词,我不想直接在take_while
参数中编写它。相反,我想从函数返回闭包。
我似乎无法让这个工作。这是我天真的尝试:
fn clos(a: char) -> Box<Fn(char) -> bool> {
Box::new(move |b| a != b)
}
fn main() {
// println!("{}", clos('a')('b')); // <-- true
// ^--- Using the closure here is fine
let s = "hello!";
let mut iter = s.chars();
let s2 = iter.take_while( clos('o') ).collect::<String>();
// ^--- This causes lots of issues
println!("{}", s2);
}
但是,它导致的错误已经证明难以理解:
error[E0277]: the trait bound `for<'r> Box<std::ops::Fn(char) -> bool>: std::ops::FnMut<(&'r char,)>` is not satisfied
--> <anon>:11:23
|
11 | let s2 = iter.take_while( clos('o') ).collect::<String>();
| ^^^^^^^^^^ trait `for<'r> Box<std::ops::Fn(char) -> bool>: std::ops::FnMut<(&'r char,)>` not satisfied
error[E0277]: the trait bound `for<'r> Box<std::ops::Fn(char) -> bool>: std::ops::FnOnce<(&'r char,)>` is not satisfied
--> <anon>:11:23
|
11 | let s2 = iter.take_while( clos('o') ).collect::<String>();
| ^^^^^^^^^^ trait `for<'r> Box<std::ops::Fn(char) -> bool>: std::ops::FnOnce<(&'r char,)>` not satisfied
|
= help: the following implementations were found:
= help: <Box<std::boxed::FnBox<A, Output=R> + 'a> as std::ops::FnOnce<A>>
= help: <Box<std::boxed::FnBox<A, Output=R> + Send + 'a> as std::ops::FnOnce<A>>
error: no method named `collect` found for type `std::iter::TakeWhile<std::str::Chars<'_>, Box<std::ops::Fn(char) -> bool>>` in the current scope
--> <anon>:11:47
|
11 | let s2 = iter.take_while( clos('o') ).collect::<String>();
| ^^^^^^^
|
= note: the method `collect` exists but the following trait bounds were not satisfied: `Box<std::ops::Fn(char) -> bool> : std::ops::FnMut<(&char,)>`, `std::iter::TakeWhile<std::str::Chars<'_>, Box<std::ops::Fn(char) -> bool>> : std::iter::Iterator`
error: aborting due to 3 previous errors
我尝试过其他一些事情,包括使用FnBox
,但它没有用。我没有那么多地使用闭包,所以我真的想了解出了什么问题,以及如何修复它。
答案 0 :(得分:8)
您的代码中存在两个问题。
首先,take_while
通过引用函数传递值(注意&
中的where P: FnMut(&Self::Item) -> bool
),而你的闭包期望按值接收它。
fn clos(a: char) -> Box<Fn(&char) -> bool> {
Box::new(move |&b| a != b)
}
然后是Box<Fn(&char) -> bool>
未实现FnMut(&char) -> bool
的问题。如果我们查看FnMut
的文档,我们会看到标准库提供了这些实现:
impl<'a, A, F> FnMut<A> for &'a F where F: Fn<A> + ?Sized
impl<'a, A, F> FnMut<A> for &'a mut F where F: FnMut<A> + ?Sized
好的,因此FnMut
实现了对Fn
实现的引用。我们手中有一个Fn
特征对象,它实现了Fn
,所以没关系。我们只需将Box<Fn>
转换为&Fn
即可。我们首先需要取消引用生成左值的框,然后引用此左值来生成&Fn
。
fn main() {
let s = "hello!";
let iter = s.chars();
let s2 = iter.take_while(&*clos('o')).collect::<String>();
println!("{}", s2);
}