【发布时间】:2021-08-03 18:48:40
【问题描述】:
我得到了这段代码,它创建了一个结构体,其中包含一个 Command 类型的字段。该结构实现了 Clone 特征。
use std::process::Command;
struct Instruct {
command: Command
}
impl Clone for Instruct {
fn clone(&self) -> Self {
Self {
command: self.command.clone() // this causes an error
}
}
}
impl Instruct {
fn new(cmd: &str) -> Instruct {
let command = Command::new(cmd);
Instruct {
command
}
}
}
fn main() {
let mut child1 = Instruct::new("sh");
let mut child2 = child1.clone(); // this errors of course
child1.command.arg("echo hello A");
child2.command.arg("echo hello B");
}
但这不起作用,因为 Command 上不存在 Copy and Clone trait,所以它不能被复制,也不能调用 clone 方法。
std::process::Command, which does not implement the Copy trait
OR
no method named `clone` found for struct `std::process::Command` in the current scope
我所追求的是声明结构 Instruct 一次,我希望能够克隆它并多次使用命令字段。
是否可以对 Command 或持有它的结构实现 Copy 和 Clone trait?
【问题讨论】:
-
由于特定于操作系统的实现,Rust 不提供命令克隆,尝试克隆一个非常可疑并且可能不安全。如果您真的想要“命令”克隆,您应该创建一个类似命令的结构,其中包含您要修改的所有内容的字段,然后在您想使用它时将其实际转换为
Command。 -
@Stargateur 没有解释如何
Clone/Copy会在这个包装器类型上实现吗?问题中已经使用了一个包装器类型。
标签: rust