我正在尝试为类似JSON的结构实现Iterator。 Rust抱怨无法推断适当的寿命。我不明白这个问题,不胜感激。我需要添加更多详细信息,但我不太了解这个问题。
--> src/ipld.rs:92:44
|
92 | if let Some(iter) = self.stack.last() {
| ^^^^
|
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 87:6...
--> src/ipld.rs:87:6
|
87 | impl<'a> Iterator for IpldIter<'a> {
| ^^
= note: ...so that the types are compatible:
expected &[std::boxed::Box<dyn std::iter::Iterator<Item = &ipld::Ipld>>]
found &[std::boxed::Box<(dyn std::iter::Iterator<Item = &'a ipld::Ipld> + 'static)>]
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected std::boxed::Box<(dyn std::iter::Iterator<Item = &'a ipld::Ipld> + 'static)>
found std::boxed::Box<dyn std::iter::Iterator<Item = &ipld::Ipld>>
pub enum Ipld {
List(Vec<Ipld>),
Bool(bool),
}
pub struct IpldIter<'a> {
stack: Vec<Box<dyn Iterator<Item = &'a Ipld>>>,
}
impl<'a> IpldIter<'a> {
fn new(ipld: &'a Ipld) -> Self {
let iter = vec![ipld].into_iter();
Self {
stack: vec![Box::new(iter)],
}
}
}
impl<'a> Iterator for IpldIter<'a> {
type Item = &'a Ipld;
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(iter) = self.stack.last() {
if let Some(ipld) = iter.next() {
match ipld {
Ipld::List(list) => {
self.stack.push(Box::new(list.iter()));
}
_ => {}
}
return Some(ipld);
} else {
self.stack.pop();
}
} else {
return None;
}
}
}
}
答案 0 :(得分:0)
Box<dyn Iterator<Item = &'a Ipld>>
具有隐式的静态生存期。通过将生存期更改为与包含的生存期“ a”相同,可以解决此问题。