I have a function to read file content. I need to return the content from this function by reference and I just can't figure out how to create mutable String
with certain lifetime inside the function.
fn main() {
let filename = String::new();
let content: &String = read_file_content(&filename);
println!("{:?}", content);
}
fn read_file_content<'a>(_filename: &'a String) -> &'a String {
let mut content: &'a String = &String::new();
//....read file content.....
//File::open(filename).unwrap().read_to_string(&mut content).unwrap();
return &content;
}
Output:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:8:36
|
8 | let mut content: &'a String = &String::new();
| ^^^^^^^^^^^^^ does not live long enough
...
14 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 7:1...
--> src/main.rs:7:1
|
7 | / fn read_file_content<'a>(_filename: &'a String) -> &'a String {
8 | | let mut content: &'a String = &String::new();
9 | |
10 | | //....read file content.....
... |
13 | | return &content;
14 | | }
| |_^