8.5 Default Parameters and Named Arguments

Unlike some other languages, Rust does not support default parameter values or named arguments. You must supply all parameters in the exact order specified by the function signature.

8.5.1 Workarounds with Option<T> or Builder Patterns

If you want “default” or “optional” behavior, you can simulate it:

Using Option<T>

fn display(message: &str, repeat: Option<u32>) {
    let count = repeat.unwrap_or(1);
    for _ in 0..count {
        println!("{}", message);
    }
}

fn main() {
    display("Hello", None);      // Uses default 1
    display("Goodbye", Some(3)); // Repeats 3 times
}

Using a Builder Pattern

struct DisplayConfig {
    message: String,
    repeat: u32,
}

impl DisplayConfig {
    fn new(msg: &str) -> Self {
        DisplayConfig {
            message: msg.to_string(),
            repeat: 1,
        }
    }

    fn repeat(mut self, times: u32) -> Self {
        self.repeat = times;
        self
    }

    fn show(&self) {
        for _ in 0..self.repeat {
            println!("{}", self.message);
        }
    }
}

fn main() {
    DisplayConfig::new("Hello").show();           // repeat=1
    DisplayConfig::new("Hi").repeat(3).show();    // repeat=3
}

Both approaches let you specify certain parameters as optional or configurable while preserving Rust’s strict type and ownership rules.