gpt4 book ai didi

rust - 隐性特征容器的不适当生命周期

转载 作者:行者123 更新时间:2023-12-03 11:35:21 25 4
gpt4 key购买 nike

该代码用于递归地迭代所包含的特征

trait Getter<'a>{
fn get(&self, index:usize)->&'a dyn Getter<'a>;
}
struct GetterImpl{
children: Vec<GetterImpl>
}

impl<'a> Getter<'a> for GetterImpl{
fn get(&self, index: usize) -> &'a dyn Getter<'a> {
self.children.get(index).unwrap()
}
}

impl GetterImpl{
pub fn create(&mut self, v: Vec<GetterImpl>){
self.children = v;
}
}
我收到错误消息:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> mytest/main/src/main.rs:10:23
|
10 | self.children.get(index).unwrap()
| ^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 9:5...
--> mytest/main/src/main.rs:9:5
|
9 | / fn get(&self, index: usize) -> &'a dyn Getter<'a> {
10 | | self.children.get(index).unwrap()
11 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> mytest/main/src/main.rs:10:9
|
10 | self.children.get(index).unwrap()
| ^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 8:6...
--> mytest/main/src/main.rs:8:6
|
8 | impl<'a> Getter<'a> for GetterImpl{
| ^^
= note: expected `&'a (dyn Getter<'a> + 'a)`
found `&dyn Getter<'a>`
...
我不明白这个错误。容器的生命周期应该比包含的容器长吗?谢谢!

最佳答案

您只需要将&self方法中的get()都更改为&'a self,因为否则,借用了self的生命周期与'a无关。

关于rust - 隐性特征容器的不适当生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63147602/

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