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(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");
}
error[E0599]: no method named `as_os_str` found for type `P` in the current scope
  --> src/main.rs:50:23
   |
50 |             .arg(path.as_os_str())
   |                       ^^^^^^^^^

Command::Arg 需要一个 OsStr,但出于某种原因我无法将 Path 转换为 OsStr(与 AsRef 有关?)

最佳答案

如果您阅读 Command::arg 的签名,您可以看到它接受的类型。它是可以作为 OsStr 引用的任何类型:

pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command

如果您查看 implementors of AsRef , 你会看到 Path是一个:

impl AsRef<OsStr> for PathBuf {}
impl AsRef<OsStr> for Path {}

回到你的问题:

How do I pass a Path to Command::arg?

通过 传递 Patharg :

fn process(path: &Path) {
    let output = Command::new("gunzip")
        .arg("--stdout")
        .arg(path)
        .output()
        .expect("failed to execute process");
}

您的问题是您接受了通用 P只能保证实现一个特征:P: AsRef<Path> . 这不是 Path 。这就是错误消息告诉您没有方法 as_os_str 的原因

error[E0599]: no method named `as_os_str` found for type `P` in the current scope

对于这种类型你唯一能做的就是调用as_ref .这将返回 &Path :

let output = Command::new("gunzip")
    .arg("--stdout")
    .arg(path.as_ref())
    .output()
    .expect("failed to execute process");

关于rust - 如何将路径传递给 Command::arg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50597033/

相关文章:

assembly - 如何将 x86 GCC 风格的 C 内联汇编转换为 Rust 内联汇编?

iterator - 如何向 Iterator 添加新方法?

lambda - 传递和评估防 rust 封闭

rust - 如何从自定义结构向量中删除重复项?

android - 无法解析相应的 JNI 函数 Java_com_mozilla_greetings_RustGreetings_greeting

rust - 我如何使用特征方法的默认实现而不是类型的自定义实现?

rust - Rust的确切自动引用规则是什么?

multithreading - Rust mpsc::Sender 不能在线程间共享?

rust - 装箱对象的返回向量

enums - 我可以匹配所有具有相同值形状的枚举变体吗?