What is the reason the following code compiles fine, despite both the lifetimes 'a and 'b being independent of each other?
struct Foo<'a> {
i: &'a i32
}
fn func<'a, 'b>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}
fn main() {}
If I make the reference i in Foo mutable, it gives the following error.
5 | fn func<'a, 'b>(x: &'a Foo<'b>) -> &'b i32 {
| ----------- -------
| |
| this parameter and the return type are declared with different lifetimes...
6 | x.i
| ^^^ ...but data from `x` is returned here
What is the reason it gives the above error?. Does it consider it's ownership over mutable reference and it sees that something (from Foo) is being taken out (with an independent lifetime), which is not possible, hence the error ?
This code (which I thought would pass) fails too:
struct Foo<'a> {
i: &'a mut i32
}
fn func<'a, 'b: 'a>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}
fn main() {}
fails with error:
error[E0623]: lifetime mismatch
--> src/main.rs:6:5
|
5 | fn func<'a, 'b: 'a>(x: &'a Foo<'b>) -> &'b i32 {
| -----------
| |
| these two types are declared with different lifetimes...
6 | x.i
| ^^^ ...but data from `x` flows into `x` here
But this one passes:
struct Foo<'a> {
i: &'a mut i32
}
fn func<'a: 'b, 'b>(x: &'a Foo<'b>) -> &'b i32 {
x.i
}
fn main() {}
This seems a bit counter-intuitive to me. Here, the outer lifetime ('a) may outlive the inner lifetime ('b). Why is this not an error?