我在定义一个从select crate,v0.2.2中返回Node
向量的函数时遇到了问题。我一直在添加这个函数,因为我已经通过错误消息(在线其他问题的帮助),但我无法弄清楚如何将'a
生命周期变量分配给返回值:< / p>
extern crate select;
use select::document::Document;
use select::predicate::*;
fn elems_by_class<'a, Node>(document: &'a Document, class: &str) -> Vec<Node<>>
where Vec<Node>: std::iter::FromIterator<select::node::Node<'a>>
{
document.find(Attr("class", class)).iter().collect::<Vec<Node<>>>()
}
fn main() {}
我得到的错误是
error: borrowed value does not live long enough
--> src/main.rs:9:5
|
9 | document.find(Attr("class", class)).iter().collect::<Vec<Node<>>>()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ temporary value created here
10 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the block at 8:0...
--> src/main.rs:8:1
|
8 | {
| ^
如何为函数调用分配'a
生命周期?我尝试(不成功)使用变量,但读取在函数体内创建的变量可能会导致问题,因此放弃了这种方法。我是否在借用洞中挖了太远,是否应该以更简单的方式定义此功能?
答案 0 :(得分:3)
您的核心问题是,您已经定义了隐藏真实 Node
的通用类型:
fn elems_by_class<'a, Node>(document: &'a Document, class: &str)
// ^^^^ -- no!
此 应该是Expected type parameter, found u8, but the type parameter is u8的副本。
但是,选择库(版本0.2.2和0.3.0)似乎有一个错误:
impl<'a> Selection<'a> {
fn iter(&'a self) -> Iter<'a>;
}
这会强制迭代器返回的值的生命周期与Selection
结构相关联,而不是Document
。
现在have been fixed显示:
impl<'a> Selection<'a> {
pub fn iter<'sel>(&'sel self) -> Iter<'sel, 'a>;
}
但是修复程序还没有发布,所以除了让维护者发布新版本之外你不能做任何事情,或者你可以选择使用git仓库中的库。