gpt4 book ai didi

rust - 如何修复 'Conflicting lifetime requirements'

转载 作者:行者123 更新时间:2023-11-29 08:30:55 24 4
gpt4 key购买 nike

我正在尝试为类似 JSON 的结构实现迭代器。 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;
}
}
}
}

最佳答案

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

关于rust - 如何修复 'Conflicting lifetime requirements',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58031951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com