我无法解决我的代码的问题。我试图通过做一个项目来制作一个CLI应用程序来学习rust,我一直收到错误E0515
下面是我的代码:
use std::path::Display;
use std::fs;
fn read_file(path: &str) -> String {
fs::read_to_string(path)
.expect("Should have been able to read the file")
}
fn list_dir(path: &str) -> Vec<Display>{
let paths = fs::read_dir(path).unwrap();
let mut dirs: Vec<Display> = vec![];
for path in paths {
dirs.push(path.unwrap().path().display());
}
dirs
}
fn main() {
println!("{}",list_dir("C:").len())
}
编译器告诉我,我返回了一个引用list_dir
函数所拥有的数据的值:
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:15:5
|
13 | dirs.push(path.unwrap().path().display());
| -------------------- temporary value created here
14 | }
15 | dirs
| ^^^^ returns a value referencing data owned by the current function
我尝试了一些方法来改变函数的返回类型,但没有一个有效。
有人能告诉我我哪里做错了吗?
1条答案
按热度按时间vq8itlhq1#
std::path::Display借用a
Path
。你可以告诉它,因为它在生命周期内是通用的(Display<'a>
)。但你的问题更深。如果你尝试做这样的事情:这仍然会编译失败,你会得到以下错误:
这里的问题是
fs::read_dir
返回一个迭代器,它产生ReadDir结构,您可以使用方法ReadDir::path从其中获取PathBuf(OS路径的owned表示)。但是,您不能存储对这些
PathBuf
的引用,因为它们将在下一次迭代中被删除。现在你要问自己,你想做什么?如果你想返回这些路径的向量(我猜这就是你想要的),只需返回
Vec<PathBuf>
。如果你想使用std::path::Display
实现来获取路径的utf-8表示,返回一个String
s的向量,然后在push
调用中简单地调用to_string
。