"Value dropped while borrowed" as a lifetime mismatch

⚓ Rust    📅 2026-05-17    👤 surdeus    👁️ 1      

surdeus

I was reading this question and it got me thinking: how can that issue be explained as a lifetime mismatch?

fn main() {
    let longest;

    let string1 = String::new();
    let str1 = &string1;
    {
        let string2 = String::new();
        let str2 = &string2;
        longest = str2;
    }
    println!("{str1}");
    println!("{longest}");
}

fn longer<'a>(str1: &'a str, str2: &'a str) -> &'a str {
    str2
}

In the 'nomicon, it states that specifying an input lifetime and an output lifetime that are the same is saying that the function can produce a reference to a value of the output type that lives just as long, or longer, than the value behind the input reference(s). This doesn't really make sense: which input referent must the output one live as long as? If it must live as long as *str2, then it does, but still complains. If it must live as long as str1, then the below example wouldn't pass the borrow check, but it does. If it means that *str1 and *str2 must live for the same time, then that means that this wouldn't be viable:

fn main() {
    let longest;

    let string1 = String::new();
    let str1 = &string1;
    {
        let string2 = String::new();
        let str2 = &string2;
        longest = str2;
        println!("{longest}");
    }
    println!("{str1}");
    
}

fn longer<'a>(str1: &'a str, str2: &'a str) -> &'a str {
    str2
}

but it is, because, obviously, longest doesn't outlive *str1 or *str2. But that isn't explained by the 'nomicon.

This makes sense to me:

fn longer<'a>(str1: &'a str, str2: &'b str) -> &'a str
where 'b: 'a
{
    str2
}

used in the first snippet, where it doesn't compile, because we explicitly say that 'b must live as long or longer than 'a, but that is untrue, making the borrowck upset. And this makes perfect sense to me.

However, it's the first snippet that I don't know how to explain as a breakage of what we promised with specifying the lifetimes.

Any help is greatly appreciated!

Thanks.

1 post - 1 participant

Read full topic

🏷️ Rust_feed