Need help with let binding does not live long enough

I have some code that lokk like this:

let file_con: &[u8] = fs::read(i).unwrap().as_ref();
let digest = sha1_digest(file_con);

sha1_digest has a signature that requires the input type to implement the Read trait. No matter what I tried, I got the error that file_con does not live long enough. What am I doing wrong?

Where is sha1_digest coming from? If it is your own function, could you please share it as well?

Sorry, this is the function:

fn sha1_digest<R: Read>(mut reader: R) -> Result<Digest, std::io::Error> {
    let mut context = Context::new(&SHA1_FOR_LEGACY_USE_ONLY);
    let mut buffer = [0; 1024];

    loop {
        let count = reader.read(&mut buffer)?;
      
        if count == 0 {
            break;
        }
        context.update(&buffer[..count]);
    }

    Ok(context.finish())
}

Is this the error message you get on your machine?

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:22:27
   |
22 |     let file_con: &[u8] = fs::read("foo").unwrap().as_ref();
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
   |                           |
   |                           creates a temporary value which is freed while still in use
23 |     let _ = sha1_digest(file_con);
   |                         -------- borrow later used here
   |
help: consider using a `let` binding to create a longer lived value
   |
22 ~     let binding = fs::read("foo").unwrap();
23 ~     let file_con: &[u8] = binding.as_ref();
   |

For more information about this error, try `rustc --explain E0716`.

(the error I get from this playground)

If that's the case, here a fixed playground.

Not quite, I would provide error logs, but I found a way around the error. I will close the topic.

Instead of reading into a Vec<u8> I open the file with File::open.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.