Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何向Command::arg传递路径?_Rust - Fatal编程技术网

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");