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?