What is it mean "extend" in "Limits of Lifetimes" on rust nomicon? #35
-
In this article https://doc.rust-lang.org/nomicon/lifetime-mismatch.html#improperly-reduced-borrows struct Foo;
impl Foo {
fn mutate_and_share<'a>(&'a mut self) -> &'a Self { &'a *self }
fn share<'a>(&'a self) {}
}
fn main() {
'b: {
let mut foo: Foo = Foo;
'c: {
let loan: &'c Foo = Foo::mutate_and_share::<'c>(&'c mut foo);
'd: {
Foo::share::<'d>(&'d foo);
}
println!("{:?}", loan);
}
}
}
From what I see, the Define extend:
I hope it's ok to ask rust questions here. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
'x doesn't mean the block has lifetime 'x, but the block can at most live as long as 'x. So the &mut foo can live as long as 'c Then for the very basic rules that you cannot have mutable and immutable reference at same time. Borrow checker needs to prove whether it can reduce the lifetime of foo so that it doesn't collide with the lifetime of the immutable borrow. If it proves that, the &mut foo is done before the &foo then there's no conflict and it compiles. If you move the "println" before &foo (and if there's no use or the mutable borrow after that), the lifetime of &mut foo would ends before &foo. That doesn't violate the rules and it will compile. But currently "println" needs to use the variable "loan" after &foo, "loan" has to be valid at the call site. So the &mut foo has to live no shorter than that. That's what extend means. |
Beta Was this translation helpful? Give feedback.
'x doesn't mean the block has lifetime 'x, but the block can at most live as long as 'x.
So the &mut foo can live as long as 'c
Then for the very basic rules that you cannot have mutable and immutable reference at same time.
Borrow checker needs to prove whether it can reduce the lifetime of foo so that it doesn't collide with the lifetime of the immutable borrow.
If it proves that, the &mut foo is done before the &foo then there's no conflict and it compiles.
If you move the "println" before &foo (and if there's no use or the mutable borrow after that), the lifetime of &mut foo would ends before &foo. That doesn't vi…