Linking the lifetimes of self and a reference in method

In the call to the method set the lifetime parameter on the impl block is used and the lifetime of the value of w is filled in for 'a in the method signature.

No. The value of the lifetime parameter 'a is fixed at the creation of the Foo struct, and will never change as it is part of its type.

In your case, the compiler actually choses for 'a a value that is compatible with both the lifetimes of v and w. If that was not possible, it would fail, such as in this example:

fn main() {
    let v = 5;
    let mut f = Foo { x: &v };

    println!("f is {:?}", f);
    let w = 7;
    f.set(&w);

    println!("now f is {:?}", f);
}

which outputs:

error[E0597]: `w` does not live long enough
  --> src/main.rs:21:1
   |
18 |     f.set(&w);
   |            - borrow occurs here
...
21 | }
   | ^ `w` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

Exactly because the 'a lifetime imposed by v is not compatible with the shorter lifetime of w.

In the second example, by forcing the lifetime of self to be 'a as well, you are tying the mutable borrow to the lifetime 'a as well, and thus the borrow ends when all items of lifetime 'a goes out of scope, namely v and w.

Leave a Comment