Rust初学者在这里,只是做一些学习项目,我遇到了path does not live long enough
错误。我试图找到答案,但没有一个能帮助我理解我的核心问题。我尝试了多种方法来修复,但没有任何帮助。
代码行match Path::new(&path).extension().and_then(OsStr::to_str){
抛出上述错误。当我删除这行langs.insert(ext, 1);
代码时,错误就消失了。我不明白为什么那条线会引起所有的问题??
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);
},
}
}
字符串
完整错误消息:
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
型
1条答案
按热度按时间zxlwwiss1#
代码中的错误可以通过做两件事来解决:
**1.**导入相关依赖。下面的依赖关系将解决匹配问题
字符串
1.您调用了一个函数来检查temp声明,但没有定义该函数。is_safe_to_iterate在main函数中使用之前需要先定义:
if is_safe_to_iterate(temp){ continue;}
一旦你从1开始添加依赖项并定义 is_safe_to_iterate(temp) 应该做什么,你的代码就可以正常运行了。