Is it possible in Rust to create a function with a default argument?
fn add(a: int = 1, b: int = 2) { a + b }
No, Rust doesn't support default function arguments. You have to define different methods with different names. There is no function overloading either, because Rust use function names to derive types (function overloading requires the opposite).
In case of struct initialization you can use the struct update syntax like this:
use std::default::Default;
#[derive(Debug)]
pub struct Sample {
a: u32,
b: u32,
c: u32,
}
impl Default for Sample {
fn default() -> Self {
Sample { a: 2, b: 4, c: 6}
}
}
fn main() {
let s = Sample { c: 23, .. Sample::default() };
println!("{:?}", s);
}
[on request, I cross-posted this answer from a duplicated question]