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.