您的代码最直接支持Rust 1.0的翻译如下:
use std::{fs, path::Path, ffi::OsStr};
fn getList(action_dir_path: &str) -> Vec<&OsStr> {
let v = fs::read_dir(&Path::new(action_dir_path))
.unwrap()
.map(|x| x.unwrap().path().file_stem().unwrap())
.collect();
return v;
}
这会产生以下错误信息:
Rust 2015
error[E0597]: borrowed value does not live long enough
--> src/lib.rs:6:18
|
6 | .map(|x| x.unwrap().path().file_stem().unwrap())
| ^^^^^^^^^^^^^^^^^ - temporary value only lives until here
| |
| temporary value does not live long enough
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 3:1...
--> src/lib.rs:3:1
|
3 | / fn getList(action_dir_path: &str) -> Vec<&OsStr> {
4 | | let v = fs::read_dir(&Path::new(action_dir_path))
5 | | .unwrap()
6 | | .map(|x| x.unwrap().path().file_stem().unwrap())
7 | | .collect();
8 | | return v;
9 | | }
| |_^
Rust 2018
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:6:18
|
6 | .map(|x| x.unwrap().path().file_stem().unwrap())
| -----------------^^^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
问题源自于
Path::file_stem
。这是其函数签名:
pub fn file_stem(&self) -> Option<&OsStr>
这表示该方法将返回对
OsStr
的
借用引用。
PathBuf
结构体是字符串的
所有者。当您离开该方法时,没有地方拥有
PathBuf
,因此它将被删除。这意味着任何引用到
PathBuf
中的内容都将不再有效。这是Rust防止您引用已释放内存的方式,值得庆幸!
最简单的方法是返回一个
Vec<String>
。
String
拥有其中的字符串,因此我们不需要担心在离开函数时会被释放:
fn get_list(action_dir_path: &str) -> Vec<String> {
fs::read_dir(action_dir_path)
.unwrap()
.map(|x| {
x.unwrap()
.path()
.file_stem()
.unwrap()
.to_str()
.unwrap()
.to_string()
})
.collect()
}
我还将样式更新(免费!)以使其更符合Rust风格:
- 使用
snake_case
来命名项
- 类型定义中冒号前不要留空格
- 没有必要设置变量再返回它。
- 除非你要从函数中提前退出,否则不要使用显式的
return
语句。
- 不需要在
Path
中包装路径。
然而,我不太喜欢所有的解包。我会这样编写该函数:
use std::{ffi::OsString, fs, io, path::Path};
fn get_list(action_dir_path: impl AsRef<Path>) -> io::Result<Vec<OsString>> {
fs::read_dir(action_dir_path)?
.map(|entry| entry.map(|e| e.file_name()))
.collect()
}
fn main() {
println!("{:?}", get_list("/etc"));
}
除上述更改外,还有以下内容:
- 我为输入路径使用了通用类型。
- 我返回一个
Result
以将错误传播给调用者。
- 我直接从
DirEntry
获取文件名。
- 我保留
OsString
类型。