Lifetime confusion

I am new to rust and have the following confusion in understanding lifetime.
What is the difference between passing String::from("hi").as_str() and "hi" when the function argument requires &str?

For example.

fn main() {
    let a = "hey";

    let r;
    {
        let b = String::from("hi");
        r = longest_str(a, b.as_str());
    }
    println!("longest is:{}", r);
}

fn longest_str<'x>(a: &'x str, b: &'x str) -> &'x str {
    if a.len() > b.len() {
        a
    } else {
        b
    }
}

will report an error: b does not live long enough.

However.

fn main() {
    let a = "hey";

    let r;
    {
        let b = "hi";
        r = longest_str(a, b);
    }
    println!("longest is:{}", r);
}

fn longest_str<'x>(a: &'x str, b: &'x str) -> &'x str {
    if a.len() > b.len() {
        a
    } else {
        b
    }
}

works fine.

In general a reference cannot outlive the data it points to. So the &str you get from String::as_str cannot outlive the String. In contrast, literals like "hi" live forever, so you can get a &str that lasts forever -- a &'static str.

In the case for String:

But with "hi":

3 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.