【问题标题】:Can we implement the Copy and Clone traits to Command struct?我们可以实现 Command 结构的 Copy 和 Clone 特征吗?
【发布时间】: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


【解决方案1】:

不,实现CopyClone 是不可能的,因为Command 本身没有实现CopyCloneCommand 实现这些类型中的任何一个都没有意义,因为它拥有拥有的数据和闭包。以下是 Command 在 Unix 平台上的封装:

pub struct Command {
    program: CString,
    args: Vec<CString>,
    argv: Argv,
    env: CommandEnv,
    cwd: Option<CString>,
    uid: Option<uid_t>,
    gid: Option<gid_t>,
    saw_nul: bool,
    closures: Vec<Box<dyn FnMut() -> io::Result<()> + Send + Sync>>,
    groups: Option<Box<[gid_t]>>,
    stdin: Option<Stdio>,
    stdout: Option<Stdio>,
    stderr: Option<Stdio>,
}

【讨论】:

    猜你喜欢
    • 2016-05-29
    • 2018-02-20
    • 1970-01-01
    • 2020-01-20
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多