1

I am a beginner in Rust and I am having a little trouble in understanding the concepts of borrow and lifetime.

I wrote this pretty straightforward code to read the contents of a file into a byte array.

fn file_to_bytes(filepath: &str)-> &[u8] {
    let mut s = String::new();
    let mut f = File::open("/home/rajiv/CodingIsFun/server/src/".to_owned()+filepath).unwrap();

    f.read_to_string(&mut s);
    let slice = s.as_str() ; 
    let bytes :&[u8] = slice.as_bytes() ;
    bytes
}

Its giving the following error.

 error: `s` does not live long enough
  --> src/main.rs:36:17
   |
36 |     let slice = s.as_str() ; 
   |                 ^ does not live long enough
...
40 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 31:41...
  --> src/main.rs:31:42
   |
31 | fn file_to_bytes(filepath: &str)-> &[u8] {

I referred this thread on reddit which says that the variables declared later are destroyed first and therefore their lifetime will be shorter than the ones declared above, and this causes the error. But I still couldn't understand what is wrong with my code.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
natcomp256
  • 706
  • 7
  • 13
  • 1
    Please check whether the linked question answers your questions. If not, please describe what you still don't understand. If you know other programming languages (notably C and C++), it would be great to let us know as we could possibly phrase the explanations in a more tailored way. – Matthieu M. Mar 02 '17 at 10:29
  • The duplicate tells you why this is not possible, you should definitely read it! In your case, the simple solution is to return `Vec` instead of `&[u8]`. The former is an *owned* type, while the latter is *borrowed*. – Lukas Kalbertodt Mar 02 '17 at 10:30
  • @LukasKalbertodt Thanks! That helped. Anyways, I think I have to read the ownership module again. – natcomp256 Mar 03 '17 at 12:27
  • @MatthieuM. I know C and C++. I think I'll read the concepts again and comeback if I still can't figure out. Thanks. – natcomp256 Mar 03 '17 at 12:28
  • @Rajivteja: Coming from C and C++, Rust's `String` is C++ `std::string` and Rust's `&[u8]` is roughly C++ `char const*` (with size). Here, you would be returning a pointer into a local `std::string`, and the `std::string` would be destroyed at the end of the function... thus leading to a dangling pointer. – Matthieu M. Mar 03 '17 at 12:44

0 Answers0