Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this an error in the Rust lifetime system, or do I just not understand lifetimes

The following function is a typical example given when explaining lifetimes.

fn longest_string<'a>(s1: &'a str, s2: &'a str) -> &'a str {
    if s1.len() >= s2.len() {
        s1
    } else {
        s2
    }
}

From the Rust documentation (https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) we can read the following: "The concrete lifetime that is substituted for ‘a is the part of the scope of s1 that overlaps with the scope of s2. In other words, the generic lifetime ‘a will get the concrete lifetime that is equal to the smaller of the lifetimes of s1 and s2."

Given the above description, how is it that the following example compiles??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fn main() {
    let res;
    let s1 = "Hello";
    {
        let s2 = "World!!";
        res = longest_string(s1, s2);
        println!("{} is longer", res);
    }

    println!("Finished with {} and with {}", s1, res); 
    // lifetime of 'res' should be tied to s2, and thus have expired ??
}

It seems to me that the lifetime of ‘res’ should have ended when s2 went out of scope, and caused a compiler error on the last line, but that didn’t happen. This compiles (and runs) without errors.

Can someone explain why?

>Solution :

Your example works, because strings literals in rust have type &'static str. So even that s2 is in separate block it has the same lifetime as s1. If you instead create String inside inner block and passed it’s reference you would get en error that you expected.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading