Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't the lifetimes be inferred in Rust?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading