I am trying to understand how lifetimes in Rust affect Structs. Attached is a minimal example that confuses me.
I would like to give a struct a reference to an object and then later it is necessary to change this object. Since it is not possible to change the object while it is borrowed, I thought that I have to remove the reference while changing it. So my idea was to define the variable as an option and remove the reference during the modification of the object by setting it to None. For the example without the use of a Struct this seems to work.
However, if I now put this reference into a Struct it does not work. It seems to me that the borrow checker overlooks the fact that the variable string is no longer borrowed. Is there a way to still achieve the desired behaviour with a Struct?
This works (link to playground):
fn main() {
let mut string = "mutable string".to_string();
let mut ref_to_string: Option<&str> = Some(&string);
ref_to_string = None;
string = "mutated string".to_string();
ref_to_string = Some(&string);
}
However, this doesn't work link to playground:
struct Foo<'a> {
pub ref_data: Option<&'a str>,
}
fn main() {
let mut string = "mutable string".to_string();
let mut foo = Foo{ref_data: Some(&string)};
foo.ref_data = None;
string = "mutated string".to_string();
foo.ref_data = Some(&string);
}
Error message:
error[E0506]: cannot assign to `string` because it is borrowed
--> src/main.rs:11:5
|
9 | let mut foo = Foo{ref_data: Some(&string)};
| ------- borrow of `string` occurs here
10 | foo.ref_data = None;
11 | string = "mutated string".to_string();
| ^^^^^^ assignment to borrowed `string` occurs here
12 | foo.ref_data = Some(&string);
| ---------------------------- borrow later used here
For more information about this error, try `rustc --explain E0506`.
Option, you don't even needref_to_string = None;. The compiler doesn't care ifref_to_stringcontains a dangling reference as long as you don't try to use it.