Why are explicit lifetimes needed in Rust?

前端 未结 10 1200
别那么骄傲
别那么骄傲 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:36

    Let's have a look at the following example.

    fn foo<'a, 'b>(x: &'a u32, y: &'b u32) -> &'a u32 {
        x
    }
    
    fn main() {
        let x = 12;
        let z: &u32 = {
            let y = 42;
            foo(&x, &y)
        };
    }
    

    Here, the explicit lifetimes are important. This compiles because the result of foo has the same lifetime as its first argument ('a), so it may outlive its second argument. This is expressed by the lifetime names in the signature of foo. If you switched the arguments in the call to foo the compiler would complain that y does not live long enough:

    error[E0597]: `y` does not live long enough
      --> src/main.rs:10:5
       |
    9  |         foo(&y, &x)
       |              - borrow occurs here
    10 |     };
       |     ^ `y` dropped here while still borrowed
    11 | }
       | - borrowed value needs to live until here
    

提交回复
热议问题