Lifetimes and matched expressions


Why does the following code (using the syntex_syntax crate) not compile with the error error: 'parse_sess' does not live long enough:

let parse_sess = syntax::parse::ParseSess::new();

if let Ok(ref the_crate) = syntax::parse::parse_crate_from_source_str(
  "some_crate".to_string(), "fn main() {}".to_string(), 
  Vec::new(), &parse_sess) {

While the following code, which simply binds the matched expression syntax::parse::parse_crate_from_source_str("some_crate".to_string(), "fn main() {}".to_string(), Vec::new(), &parse_sess) to a local let binding, does compile:

let parse_sess = ParseSess::new();
let result = syntax::parse::parse_crate_from_source_str(
    "some_crate".to_string(), "fn main() {}".to_string(),
    Vec::new(), &parse_sess);

if let Ok(ref the_crate) = result {

The same problem is encountered when using match instead of if let. I’ve tried hard to duplicate this problem using simpler but similar structs which have the same lifetimes as their session fields but the same problem never occurs.

I’m fine with using the second working code snippet, but am curious as to why it doesn’t work. I don’t see any reason why the first code snippet does not compile when the second one does.


Is the if let the last expression in the enclosing function? If so then you might be running into #21114 or a related compiler bug.


That seems to be the problem here as the if let was, indeed, the last expression in the function. Thanks for the reply!