Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the lifetimes be inferred in Rust?

Tags:

rust

lifetime

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 ?

like image 754
Gianluca Fuoco Avatar asked Dec 31 '25 15:12

Gianluca Fuoco


1 Answers

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.

like image 97
kumarmo2 Avatar answered Jan 02 '26 05:01

kumarmo2