Rust 如何向Command::arg传递路径?
经过长时间的休息,我又开始生锈了。我正在努力做到以下几点:Rust 如何向Command::arg传递路径?,rust,Rust,经过长时间的休息,我又开始生锈了。我正在努力做到以下几点: use std::fs; use std::path::Path; use std::process::Command; fn main() { let paths = fs::read_dir("SOME_DIRECTORY").unwrap(); for path in paths { let full_path = path.unwrap().path(); process(ful
use std::fs;
use std::path::Path;
use std::process::Command;
fn main() {
let paths = fs::read_dir("SOME_DIRECTORY").unwrap();
for path in paths {
let full_path = path.unwrap().path();
process(full_path);
}
}
fn process<P: AsRef<Path>>(path: P) {
let output = Command::new("gunzip")
.arg("--stdout")
.arg(path.as_os_str())
.output()
.expect("failed to execute process");
}
命令::Arg
需要一个OsStr,但由于某种原因,我无法将路径转换为OsStr(与AsRef有关?如果您阅读其签名,您可以看到它接受的类型。它是可作为OsStr
引用的任何类型:
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command
回到你的问题:
如何向Command::arg传递路径
通过将路径
传递到arg
:
您的问题是您接受了一个通用的
p
,它只保证实现一个特性:p:AsRef
。它不是路径
。这就是为什么错误消息告诉您没有方法as\u os\u str
error[E0599]:在当前作用域中找不到类型为'P'的名为'as_os_str'的方法
对于这种类型,您唯一能做的就是调用作为\u ref
。这将返回一个路径:
let output = Command::new("gunzip")
.arg("--stdout")
.arg(path.as_ref())
.output()
.expect("failed to execute process");
这么简单。谢谢
fn process(path: &Path) {
let output = Command::new("gunzip")
.arg("--stdout")
.arg(path)
.output()
.expect("failed to execute process");
}
let output = Command::new("gunzip")
.arg("--stdout")
.arg(path.as_ref())
.output()
.expect("failed to execute process");