0

I have the following function to parse mail in Rust.

fn read_mail(fname: &Path) -> Result<mailparse::ParsedMail, mailparse::MailParseError> {
    let mut f = File::open(fname).unwrap();
    let mut buf = String::new();
    let _ = f.read_to_string(&mut buf);
    mailparse::parse_mail(buf.as_bytes())
}

Here buf only lives until the function returns and parse_mail borrows it. This won't compile since the return value would outlive it's borrow.

How can I tell Rust that buf can have a longer lifetime until the return value is destroyed?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Max Linke
  • 1,705
  • 2
  • 18
  • 24
  • You haven't provided the definition of `mailparse::ParsedMail` (or **even better** a [MCVE]). My intuition says that `ParsedMail` contains a reference to the buffer, so the answer to your question is: *you can't*. – Shepmaster Dec 05 '16 at 18:52
  • See also http://stackoverflow.com/q/28820781/155423; http://stackoverflow.com/q/25464151/155423; http://stackoverflow.com/q/27570978/155423; http://stackoverflow.com/q/35666024/155423; http://stackoverflow.com/q/30330697/155423; **all** of which contain the search string "rust extend lifetime". You are expected to [perform (and then show us) your research before asking a question](http://meta.stackoverflow.com/q/261592/155423). – Shepmaster Dec 05 '16 at 18:55
  • One of [the better ways I've seen it described](https://doc.rust-lang.org/nightly/book/lifetimes.html#lifetimes): *It's important to understand that lifetime annotations are descriptive, not prescriptive. This means that how long a reference is valid is determined by the code, not by the annotations.* – Shepmaster Dec 05 '16 at 19:12

0 Answers0