Use Method Chaining

A common pattern found in Rust programs is method chaining. You can see this often with the collection-processing functions such as map(), filter(), etc., when a series of transformations need to be done for a collection.

fn main() {
    println!(
        "{}",
        [0, 1, 2, 3, 4]
            .iter()
            .map(|x| x * x)
            .filter(|x| *x > 5)
            .fold(0, |a, b| a + b)
    );
}

Here is another example that executes a command-line program.

fn main() {
    std::process::Command::new("sh")
            .arg("-c")
            .arg("echo hello")
            .output()
            .expect("failed to execute process");
}

A common way to use method chaining in your own code is to return self for your methods.