Default function arguments in Rust

前端 未结 6 457
时光取名叫无心
时光取名叫无心 2020-12-13 05:38

Is it possible in Rust to create a function with a default argument?

fn add(a: int = 1, b: int = 2) { a + b }
6条回答
  •  春和景丽
    2020-12-13 05:47

    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]

提交回复
热议问题