Why are explicit lifetimes needed in Rust?

前端 未结 10 1194
别那么骄傲
别那么骄傲 2020-11-22 16:08

I was reading the lifetimes chapter of the Rust book, and I came across this example for a named/explicit lifetime:

struct Foo<\'a> {
    x: &\'a i         


        
10条回答
  •  野性不改
    2020-11-22 16:34

    The lifetime annotation in the following structure:

    struct Foo<'a> {
        x: &'a i32,
    }
    

    specifies that a Foo instance shouldn't outlive the reference it contains (x field).

    The example you came across in the Rust book doesn't illustrate this because f and y variables go out of scope at the same time.

    A better example would be this:

    fn main() {
        let f : Foo;
        {
            let n = 5;  // variable that is invalid outside this block
            let y = &n;
            f = Foo { x: y };
        };
        println!("{}", f.x);
    }
    

    Now, f really outlives the variable pointed to by f.x.

提交回复
热议问题