在以下示例中,我遇到了弄清fn filter
函数的类型签名的麻烦。
Node和Descendant定义仅用于语法。这并不意味着做任何事情!
use std::iter::Filter;
#[derive(Clone)]
pub struct Node<'a> {
s: &'a str,
}
pub struct Descendants<'a>{
iter: Node<'a>
}
impl<'a> Iterator for Descendants<'a> {
type Item = Node<'a>;
fn next(&mut self) -> Option<Node<'a>> {
Some(Node {s: self.iter.s})
}
}
impl<'a> Node<'a> {
pub fn descendants(&self) -> Descendants<'a> {
Descendants{ iter: Node{s: self.s} }
}
pub fn filter(&self, criteria: &str) -> Filter<Descendants<'a>, fn(&'a Node<'a>)->bool > {
self.descendants()
.filter(|node| node.s == "meh")
}
}
fn main() {
let doc = Node{s: "str"};
}
我得到的错误如下:
<anon>:27:28: 27:34 error: the type of this value must be known in this context
<anon>:27 .filter(|node| node.s == "meh")
^~~~~~
<anon>:27:21: 27:43 error: mismatched types:
expected `fn(&Node<'_>) -> bool`,
found `[closure <anon>:27:21: 27:43]`
(expected fn pointer,
found closure) [E0308]
<anon>:27 .filter(|node| node.s == "meh")
^~~~~~~~~~~~~~~~~~~~~~
<anon>:27:14: 27:44 error: type mismatch: the type `fn(&Node<'_>) -> bool` implements the trait `core::ops::FnMut<(&Node<'_>,)>`, but the trait `for<'r> core::ops::FnMut<(&'r Node<'_>,)>` is required (expected concrete lifetime, found bound lifetime parameter ) [E0281]
<anon>:27 .filter(|node| node.s == "meh")
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:27:14: 27:44 error: type mismatch resolving `for<'r> <fn(&Node<'_>) -> bool as core::ops::FnOnce<(&'r Node<'_>,)>>::Output == bool`:
expected bound lifetime parameter ,
found concrete lifetime [E0271]
<anon>:27 .filter(|node| node.s == "meh")
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to 4 previous errors
playpen: application terminated with error code 101
当我按照此问题Correct way to return an Iterator?时,我尝试将pub fn filter(&self, criteria: &str) -> Filter<Descendants<'a>, fn(&'a Node<'a>)->bool >
替换为pub fn filter(&self, criteria: &str) -> ()
我
<anon>:26:9: 27:44 error: mismatched types:
expected `()`,
found `core::iter::Filter<Descendants<'_>, [closure <anon>:27:21: 27:43]>`
我应该用closure
代替什么?
或者,如果返回Filter
太难而且挑剔,如何为Wrapper
返回类型编写fn filter()
?
答案 0 :(得分:6)
我清楚地记得几次之前已经回答了这个问题(我甚至在答案a few minutes before中写了这篇文章),但我现在找不到链接,所以就这样了。
您的代码的问题在于您使用闭包作为filter()
参数:
.filter(|node| node.s == "meh")
Rust中的未装箱闭包是以匿名类型实现的,当然,这些类型无法命名,因此有 no 方式来编写函数的签名,该函数返回使用a的迭代器关闭。这就是你得到的错误信息:
expected `fn(&Node<'_>) -> bool`,
found `[closure <anon>:27:21: 27:43]`
(expected fn pointer,
found closure) [E0308]
有几种解决方法,其中一种方法是使用特征对象:
pub fn filter<'b>(&'b self, criteria: &'b str) -> Box<Iterator<Item=Node<'a>+'b>>
{
Box::new(self.descendants().filter(move |node| node.s == criteria))
}
鉴于您的闭包具有非空的环境,这是您的代码工作的唯一方法。如果你的闭包没有捕获任何东西,你可以使用一个静态函数,其类型可以写出来:
pub fn filter(&self) -> Filter<Descendants<'a>, fn(&Node<'a>) -> bool> {
fn filter_fn<'b>(node: &Node<'b>) -> bool {
node.s == "meh"
}
self.descendants().filter(filter_fn)
}