In chapter 19.2 of The Rust Programming Language, the following example compiles without any error. I found out from issue #1834 that there is a new lifetime elision rule that implicitly makes 's
longer than 'c
.
Although I couldn't find a detailed explanation of this new elision rule, I guess that it is not more than just an implicit version of the longer, more explicit constraint: <'c, 's: 'c>
. I think however my confusion is probably not about this new elision rule but of course I could be wrong about this.
My understanding is, that parse_context
takes ownership of context
as it has not been borrowed but actually moved to the function. That alone implies to me that the lifetime of context
should match the lifetime of the function it is owned by regardless of the lifetimes and constraint we defined in Context
, and Parser
.
Based on those definitions, the part where context
outlives the temporary Parser
makes perfect sense to me (after all, we defined a longer lifetime), but the part where the &str
reference is not dropped when context
goes out of scope at the end of parse_context
and I can still safely return it -- makes me puzzled.
What have I missed? How can the compiler reason about the lifetime of the returned &str
?
UPDATED EXAMPLE
struct Context<'s>(&'s str);
struct Parser<'c, 's>
{
context: &'c Context<'s>,
}
impl<'c, 's> Parser<'c, 's>
{
fn parse(&self) -> Result<(), &'s str>
{
Err(self.context.0)
}
}
fn parse_context(context: Context) -> Result<(), &str>
{
Parser { context: &context }.parse()
}
fn main()
{
let mut s = String::new();
s += "Avail";
s += "able?";
if let Err(text) = parse_context(Context(&s))
{
println!("{}", text);
}
}