Reputation: 75
Rust beginner here and just doing some learning projects, I encountered the path does not live long enough
Error. I tried to find answers, but none of them helped me understand my core problem. I tried multiple ways to fix but nothing helped.
Line of code match Path::new(&path).extension().and_then(OsStr::to_str){
throws the mentioned error . And the error specifically goes away when i remove this langs.insert(ext, 1);
line of code. I cant understand why that line causes all the problem??
main.rs (playground)
fn iterate_files(path: String, langs: &mut HashMap<&str, u16>){
let files = fs::read_dir(&path);
match &files{
Ok(_) => {
for file in files.unwrap(){
let path: PathBuf = file.unwrap().path();
let string_path: String = path.display().to_string();
let temp = Path::new(&string_path).file_name().unwrap();
if is_safe_to_iterate(temp){
continue;
}
match Path::new(&path).extension().and_then(OsStr::to_str){
None => {
iterate_files(string_path, langs);
continue;
},
Some(text) => {
let ext: &str = text;
if langs.contains_key(ext){
langs.insert(ext, 1);
}
}
}
println!("{}", path.display());
}
},
Err(_) => {
println!("Illegal File Encountered booom!! {}", path);
},
}
}
Full error message:
error[E0597]: `path` does not live long enough
--> src/lib.rs:24:33
|
12 | fn iterate_files(path: String, langs: &mut HashMap<&str, u16>) {
| - let's call the lifetime of this reference `'1`
...
24 | match Path::new(&path).extension().and_then(OsStr::to_str) {
| ^^^^^ borrowed value does not live long enough
...
32 | langs.insert(ext, 1);
| -------------------- argument requires that `path` is borrowed for `'1`
...
38 | }
| - `path` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to previous error
Upvotes: 0
Views: 327
Reputation: 108
The error with your code can be resolved by doing 2 things:
1. Import the relevant dependencies. The following dependencies would resolve the match issue among others
use hashbrown::HashMap;
use std::path::Path;
use std::fs;
use std::ffi::OsStr;
You called a function to check the temp declaration but did not define the function. is_safe_to_iterate should be defined before being used in the main function:
if is_safe_to_iterate(temp){ continue; }
Once you add the dependencies from 1 and define what is_safe_to_iterate(temp) should do your code runs fine.
Upvotes: 0