Lifetime confusion about "&c.tostring()"

I'm reading "rust for rustaceans",below is an example in the book:

struct StrSplit<'s, 'p> {
    delimiter: &'p str,
    document: &'s str,
}
impl<'s, 'p> Iterator for StrSplit<'s, 'p> {
    type Item = &'s str;
    fn next(&mut self) -> Option<Self::Item> {
        todo!()
    }
}
fn str_before(s: &str, c: char) -> Option<&str> {
    StrSplit {
        document: s,
        delimiter: &c.to_string(),
    }
    .next()
}

I'm wondering why the &c.to_string() won't throw "temporary value dropped while borrowed" error?I assume that c.to_string() will return a String value and will be dropped immediately.
Appreciate anyone who reply.

1 Like

Temporary lifetime extension. The String drops after next() is executed but before the result at the call site instantiates. Edit: see next post.

I'll clarify: this is not temporary lifetime extension. This is regular temporary lifetime.

A temporary lives until the end of a statement or, if it's in the last expression of a function (as it is in this case) then it lives until the end of the function.

4 Likes

Yep, my bad.

It makes sense! Thanks for your reply

Thanks for your reply, which helps extend my understanding of lifetime.