如何解决“有冲突的使用寿命要求”

问题描述 投票:0回答:1

我正在尝试为类似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;
            }
        }
    }
}
rust
1个回答
0
投票

Box<dyn Iterator<Item = &'a Ipld>>具有隐式的静态生存期。通过将生存期更改为与包含的生存期'a相同,可以解决此问题。

© www.soinside.com 2019 - 2024. All rights reserved.