If I try to run this:
use std::{fs, process};
fn read_file_to_vec(file_path: &str) -> Vec<&str> {
let file_string = match fs::read_to_string(file_path) {
Ok(a) => a,
Err(e) => {
eprintln!("{}", e);
process::exit(2)
}
};
file_string.split("\n").collect::<Vec<&str>>()
}
fn main() {
read_file_to_vec("/home/john/passwords.txt");
}
I get:
error[E0515]: cannot return value referencing local variable `file_string`
--> src/main.rs:11:5
|
11 | file_string.split("\n").collect::<Vec<&str>>()
| -----------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `file_string` is borrowed here
Why can I not return a vector that consumed the file_string
variable already? What should I do to move file_string
into the vector?