Rust multiple lifetimes struct can't access beyond the less longer lifetime parameter

Viewed 61
struct TwoStrRef<'a, 'b> {
    str1: &'a str,
    str2: &'b str,
}

fn main() {
    let a_ref_struct;
    let string_1 = String::from("hello");
    let str_ref;
    {
        let string_2 = String::from("world");

        a_ref_struct = TwoStrRef {
            str1: &string_1,
            str2: &string_2,
        };

        str_ref = a_ref_struct.str1;
    }

    // str_ref; // Ok

    // a_ref_struct.str1;  // Error: `string_2` does not live long enough borrowed value does not live long enough
}

there are two lifetime parameters for struct TwoStrRef, a' and 'b, and I assign the reference of string_1 and string_2 (which are in different scope and string_1 is the longer one) to field str_1 and str_2, and when I try to access a_ref_struct.str1 outside the scope of string_2 (but the same with string_1), the compiler will throw error, which indicated that string_2 does not live long enough. Isn't the str1 field holds the reference of string_1 that is not outside its scope ? And why if I assign the str1 reference to str_ref, I can access it in the same scope with string_1?

1 Answers

Isn't the str1 field holds the reference of string_1 that is not outside its scope ?

a_ref_struct is dropped before string_2 goes out of scope: this is required because otherwise any access of its str2 field (which could potentially occur in its drop handler, for example) would be invalid. Indeed if a_ref_struct were to exist after string2 is dropped, its str2 would be a reference into released memory which is Undefined Behaviour even if that reference is never accessed.

And why if I assign the str1 reference to str_ref, I can access it in the same scope with string_1?

There you are just taking a copy of the reference that is held in a_ref_struct.str1 (with lifetime 'a of string_1) and storing that copy into str_ref. a_ref_struct can then be (and is) dropped without affecting that (copied) reference.

Related