回溯特征容器的不适当生命周期
inappropriate lifetime of recusive trait container
该代码用于递归迭代包含的特征
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>`
...
我不明白这个错误。容器的寿命应该比包含的更长?谢谢!
你只需要将get()
方法中的&self
在两个地方都改为&'a self
,否则self
会被借用一个与[=无关的不同生命周期14=].
该代码用于递归迭代包含的特征
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>`
...
我不明白这个错误。容器的寿命应该比包含的更长?谢谢!
你只需要将get()
方法中的&self
在两个地方都改为&'a self
,否则self
会被借用一个与[=无关的不同生命周期14=].