Lifetime 'b: 'a not work as expected

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.

A lifetime describes how long something is borrowed, not how long the thing itself lasts. It's the region of code where the reference is allowed to exist, not the region where its referent exists.

In both your examples, the borrows begin on line 4 and end after line 5. So both references exist in the same region of code, and have the same lifetime.

7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.