I need help regarding how to convert file input taken as a string to an vector. I tried
let content = fs::read_to_string(file_path).expect("Failed to read input");
let content: Vec<&str> = content.split("\n").collect();
This works, but I wanted to convert it to one statement. Something like
let content: Vec<&str> = fs::read_to_string(file_path)
.expect("Failed to read input")
.split("\n")
.collect();
I tried using
let content: Vec<&str> = match fs::read_to_string(file_path) {
Ok(value) => value.split("\n").collect(),
Err(err) => {
println!("Error Unable to read the file {}", err);
return ();
}
};
and
let content: Vec<&str> = match fs::read_to_string(file_path) {
Ok(value) => value,
Err(err) => {
println!("Error Unable to read the file {}", err);
return ();
}
}
.split("\n")
.collect();
The compiler says that the borrowed values does not live long enough (1st) and value in freed while in use (2nd) (problem with borrowing, scope and ownership).
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:4:26
|
4 | let content: Vec<&str> = fs::read_to_string("")
| __________________________^
5 | | .expect("Failed to read input")
| |___________________________________^ creates a temporary which is freed while still in use
6 | .split("\n")
7 | .collect();
| - temporary value is freed at the end of this statement
8 |
9 | dbg!(content);
| ------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
I still lack much understanding about how to fix them.