Error due to return of reference?

I was trying to write a simple function to parse data and encounter this error:

error[E0515]: cannot return value referencing local variable `content`
  --> src/http.rs:35:30
   |
29 |     let first_line = match content.lines().next() {
   |                            ------- `content` is borrowed here
...
35 |       Err(error) => { return Err(error); }
   |                              ^^^^^^^^^^ returns a value referencing data owned by the current function

error: aborting due to previous error

I'm confused by this error because I don't understand the connection between error and content. Can someone explain to me what is my mistake?

Code:

  pub fn read(content: &[u8]) -> Result<HttpHeader, &str> {
    let content = String::from_utf8_lossy(content).to_string();

    let first_line = match content.lines().next() {
      Some(first_line) => first_line,
      None => { return Err("Start line is empty") }
    };
    let (location, method) = match read_start_line(first_line) {
      Ok((location, method)) => (location, method),
      Err(error) => { return Err(error); }
    };
    // ...

What's the signature of read_start_line. It's probably attaching a lifetime to the error type.

fn read_start_line(content: &str) -> Result<(String, HttpMethod), &str>

Yes, so the error type is probably a slice into the original string. If you meant for this to be a string literal, use &'static str as the error type. The reason why the lifetimes work out this way is because of something called lifetime elison.

// these two signatures are the same
fn read_start_line(content: &str) -> Result<(String, HttpMethod), &str>
fn read_start_line<'a>(content: &'a str) -> Result<(String, HttpMethod), &'a str>
1 Like

Thanks!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.