Lifetime Mismatches in Rust
Hello,
I am a Rust newbie, trying to learn how lifetimes work in Rust. I assume that the following example below does not compile because the lifetime of the &mut self
borrow does not match up with the lifetime parameter 'a
.
struct A(String);
struct B<'a>(A, &'a String);
impl<'a> B<'a> {
fn change(&mut self) {
self.1 = &self.0.0;
}
}
fn main() {
let a = A(String::new());
let c = String::new();
let mut b = B(a, &c);
b.change();
}
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:6:18
|
6 | self.1 = &self.0.0;
| ^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
--> src/main.rs:5:15
|
5 | fn change(&mut self) {
| ^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:6:18
|
6 | self.1 = &self.0.0;
| ^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
--> src/main.rs:4:6
|
4 | impl<'a> B<'a> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:6:18
|
6 | self.1 = &self.0.0;
| ^^^^^^^^^
For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error
So, if I set the lifetime &mut self
to 'a
, the example compiles:
struct A(String);
struct B<'a>(A, &'a String);
impl<'a> B<'a> {
fn change(&'a mut self) {
self.1 = &self.0.0;
}
}
fn main() {
let a = A(String::new());
let c = String::new();
let mut b = B(a, &c);
b.change();
}
However, if I try to print b.1
, I get an error:
struct A(String);
struct B<'a>(A, &'a String);
impl<'a> B<'a> {
fn change(&'a mut self) {
self.1 = &self.0.0;
}
}
fn main() {
let a = A(String::new());
let c = String::new();
let mut b = B(a, &c);
b.change();
println!("{}", b.1);
}
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `b.1` as immutable because it is also borrowed as mutable
--> src/main.rs:15:20
|
14 | b.change();
| ---------- mutable borrow occurs here
15 | println!("{}", b.1);
| ^^^
| |
| immutable borrow occurs here
| mutable borrow later used here
|
= note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` due to previous error
What is the lifetime of the b
mutable borrow here? I thought that because of NLL and reborrowing, the lifetime of the b
mutable borrow is restricted to that line (b.change()
).
I would greatly appreciate any response/clarity. Thank you for your time, support, and help.