Consider the following example
struct Foo {
val: &str
}
fn main() {
let hello = String::from("hello");
let foo = Foo{ val: &hello[..]};
}
This doesn't compile because a lifetime is required. A very simple fix would be the following:
struct Foo<'a> {
val: &'a str
}
Why can't the compiler assume (as a sensible default) that the reference will live as long as the struct Foo ? Are there any use cases where this would not be the case ?
Because assuming reference will live as long as the struct Foo would be plain wrong. Consider this for example.
fn main() {
let foo: Foo;
{
let string = "foo".to_string();
foo = Foo {
val: string.as_str(),
}
}
println!("{}", foo.val);
}
If compiler had assumed the "sensible default" here that string will live as long as Foo, this would compile . But we can clearly see that string will be dropped after inner loop ends but foo will live even after it.
In short, its Foo's lifetime that is dependent on the &str and not the other way around, i.e. Foo cannot outlive &str.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With