I need to return a Vector of &str from a function. To do that I return the value in a parameter that I have passed in a reference.
Here is the initial code that I want to write:
fn read_input_file(input_file: String, path_list: &mut Vec<&str>) {
let output_file =
fs::read_to_string(input_file).expect("Should have been able to read the file");
*path_list = &output_file.split('\n').collect::<Vec<&str>>();
}
I have had the following output from the compiler:
error[E0597]: `output_file` does not live long enough
--> src\main.rs:112:18
|
109 | fn read_input_file(input_file: String, path_list: &mut Vec<&str>) {
| - let's call the lifetime of this reference `'1`
...
112 | *path_list = output_file.split('\n').collect::<Vec<&str>>();
| ---------- ^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
| |
| assignment requires that `output_file` is borrowed for `'1`
113 | }
| - `output_file` dropped here while still borrowed
My tentative attempt to solve it
I have tried to add lifetime to match the advice of the compiler, here the result:
fn read_input_file<'a, 'b>(input_file: String, path_list: &'a mut Vec<&str>) {
let output_file =
fs::read_to_string(input_file).expect("Should have been able to read the file");
let split: &'b Split<'_, char> = &output_file.split('\n');
*path_list = (*split.clone().collect::<Vec<&str>>()).to_vec();
}
And now I have the following output from the compiler:
error[E0597]: `output_file` does not live long enough
--> src\main.rs:105:39
|
102 | fn read_input_file<'a, 'b>(input_file: String, path_list: &'a mut Vec<&str>) {
| -- lifetime `'b` defined here
...
105 | let split: &'b Split<'_, char> = &output_file.split('\n');
| ------------------- ^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
| |
| type annotation requires that `output_file` is borrowed for `'b`
106 | *path_list = (*split.clone().collect::<Vec<&str>>()).to_vec();
107 | }
| - `output_file` dropped here while still borrowed
error[E0716]: temporary value dropped while borrowed
--> src\main.rs:105:39
|
102 | fn read_input_file<'a, 'b>(input_file: String, path_list: &'a mut Vec<&str>) {
| -- lifetime `'b` defined here
...
105 | let split: &'b Split<'_, char> = &output_file.split('\n');
| ------------------- ^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
| |
| type annotation requires that borrow lasts for `'b`
106 | *path_list = (*split.clone().collect::<Vec<&str>>()).to_vec();
107 | }
| - temporary value is freed at the end of this statement
How can I handle this issue correctly?