gpt4 book ai didi

rust - 如何将路径传递给 Command::arg?

转载 作者:行者123 更新时间:2023-11-29 08:34:51 25 4
gpt4 key购买 nike

经过长时间的休息后,我又回到了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com