Builder Pattern Example

Very simplified version of Command, remove redundant lifetime, change String to &str, you can copy/paste and see it running.

https://doc.rust-lang.org/1.0.0/style/ownership/builders.html
https://doc.rust-lang.org/std/process/struct.Command.html

#[derive(Debug)]
pub struct Command {
    program: String,
    args: Vec<String>,
    cwd: Option<String>,
}

impl Command {
    pub fn new(program: &str) -> Command {
        Command {
            program: program.to_string(),
            args: Vec::new(),
            cwd: None,
        }
    }

    /// Add an argument to pass to the program.
    pub fn arg(&mut self, arg: &str) -> &mut Command {
        self.args.push(arg.to_string());
        self
    }

    /// Add multiple arguments to pass to the program.
    pub fn args(&mut self, args: &[&str])
                -> &mut Command {
        for arg in args {
            self.args.push(arg.to_string());
        }
        self
    }

    /// Set the working directory for the child process.
    pub fn cwd(&mut self, dir: String) -> &mut Command {
        self.cwd = Some(dir);
        self
    }
}

fn main() {
// One-liners
    Command::new("/bin/cat").arg("file.txt");

// Complex configuration
    let mut cmd = Command::new("/bin/ls");
    cmd.arg(".").args(&["/C", "echo hello"]);
    println!("{:#?}", cmd);
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.