I have some code as follows, I don't quite understand why the compiler is complaining about lifetime, can someone help me about this?
struct Entity {}
struct Container<'a> {
root_index: usize,
entities: &'a mut [Entity],
}
impl<'a> Container<'a> {
fn root(&self) -> &'a Entity {
&self.entities[self.root_index]
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/lib.rs:10:14
|
10 | &self.entities[self.root_index]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 9:9...
--> src/lib.rs:9:9
|
9 | fn root(&self) -> &'a Entity {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:10:14
|
10 | &self.entities[self.root_index]
| ^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 8:10...
--> src/lib.rs:8:10
|
8 | impl<'a> Container<'a> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:10:13
|
10 | &self.entities[self.root_index]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground`
To learn more, run the command again with --verbose.