I'm learning Rust's lifetime and playing with the following code.
#[derive(Debug)]
struct S<'a, 'b: 'a> {
a: &'a String,
b: &'b String,
}
Here I have two lifetimes with the struct and I specify 'b
should outlives 'a
. Then I test it with
let x = "x".to_string(); // line 1
{ // line 2
let y = "y".to_string(); // line 3
let o = S { a: &y, b: &x }; // line 4
println!("{:?}", o); // line 5
} // line 6
It prints S { a: "y", b: "x" }
. Here the variable x
has a larger lifetime line [1, 6] and y
has [3, 6]. So the condition 'b: 'a
was met. But when I change the program a little bit to:
let x = "x".to_string(); // line 1
{ // line 2
let y = "y".to_string(); // line 3
let o = S { a: &x, b: &y }; // line 4
println!("{:?}", o); // line 5
} // line 6
This also executes without issue and outputs S { a: "x", b: "y" }
. But this time the lifetime condition 'b: 'a
seems not met. Why this happens? Thanks.