Lifetime misunderstanding

I'm trying to learn lifetimes, and I thought I had understood, but I've just found an example that isn't supposed to compile from what I understand:

// If one of the input gets out of scope, the result will too, because it has the 
// same lifetime as the shortest input
fn returns_first<'a>(first: &'a str, second: &'a str) -> &'a str {
    first
}

fn main() {
    let c = {
        let a = "a";
        let b = "b";
        returns_first(&a, &b)
    };
    dbg!(c);
    // dbg!(a); cannot find value `a` in this scope
}

I a gets out of scope, why is c still valid, since it references a ?

"a" and "b" are already references and their type is &'static str. What you're passing to the function returns_first are not references to the variables a and b, but copies of those &'static str, and this 'a = 'static. It might be a bit misleading because the arguments are &a and &b, but those have type &'something &'static str, which gets automatically dereferences to &'static str.

You should try making a and b of type String, that way any &str you get from them will actually be tied to them.

// If one of the input gets out of scope, the result will too, because it has the 
// same lifetime as the shortest input
fn returns_first<'a>(first: &'a str, second: &'a str) -> &'a str {
    first
}

fn main() {
    let c = {
        let a = String::from("a");
        let b = String::from("b");
        returns_first(&a, &b)
    };
    dbg!(c);
    // dbg!(a); cannot find value `a` in this scope
}
2 Likes

Oh it makes sens now, thanks dor the answer

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.