mrb*_*rne 4 lifetime rust borrow-checker
编者注:这个问题在Rust 1.0之前被问过.从那时起,许多函数和类型都发生了变化,某些语言语义也发生了变化.问题中的代码不再有效,但答案中表达的想法可能是.
我正在尝试列出目录中的文件并将文件名复制到我自己的文件中Vec.我已经尝试了几种解决方案,但它总是会遇到无法创建足够长的生存变量的问题.我不明白我的错误.
fn getList(action_dir_path : &str) -> Vec<&str> {
let v = fs::readdir(&Path::new(action_dir_path))
.unwrap()
.iter()
.map(|&x| x.filestem_str().unwrap())
.collect();
return v;
}
Run Code Online (Sandbox Code Playgroud)
为什么编译器会抱怨"x"?我不在乎x,我想在&str里面,我认为&str是静态的.
我试过这种方式,但是我得到了相同的结果,编译器抱怨"路径"没有足够长的时间.
fn getList2(action_dir_path : &str) -> Vec<&str> {
let paths = fs::readdir(&Path::new(action_dir_path)).unwrap();
let mut v : Vec<&str> = Vec::new();
for path in paths.iter(){
let aSlice = path.filestem_str().unwrap();
v.push(aSlice);
}
return v;
}
Run Code Online (Sandbox Code Playgroud)
这是操场.
支持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;
}
Run Code Online (Sandbox Code Playgroud)
这会产生错误消息:
锈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 | | }
| |_^
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
问题来自于Path::file_stem.这是签名:
pub fn file_stem(&self) -> Option<&OsStr>
Run Code Online (Sandbox Code Playgroud)
这表明该方法将返回一个借来的引用OsStr.该PathBuf结构是业主的字符串.当你离开这个方法时,没有任何地方可以拥有它PathBuf,所以它将被丢弃.这意味着对PathBuf遗嘱的任何引用都不再有效.这是Rust阻止你引用不再分配的内存,对于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()
}
Run Code Online (Sandbox Code Playgroud)
我还更新了样式(免费!)更像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"));
}
Run Code Online (Sandbox Code Playgroud)
除了上面的更改:
Result将错误传播给调用者.DirEntry文件名.OsString.| 归档时间: |
|
| 查看次数: |
1922 次 |
| 最近记录: |