Default function arguments in Rust

前端 未结 6 463
时光取名叫无心
时光取名叫无心 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:59

    Another way could be to declare an enum with the optional params as variants, which can be parameterized to take the right type for each option. The function can be implemented to take a variable length slice of the enum variants. They can be in any order and length. The defaults are implemented within the function as initial assignments.

    enum FooOptions<'a> {
        Height(f64),
        Weight(f64),
        Name(&'a str),
    }
    use FooOptions::*;
    
    fn foo(args: &[FooOptions]) {
        let mut height   = 1.8;
        let mut weight   = 77.11;
        let mut name     = "unspecified".to_string();
    
        for opt in args {
            match opt {
                Height(h) => height = *h,
                Weight(w) => weight = *w,
                Name(n)   => name   =  n.to_string(),
            }
        }
        println!("  name: {}\nweight: {} kg\nheight: {} m", 
                 name, weight, height);
    }
    
    fn main() { 
    
                foo( &[ Weight(90.0), Name("Bob") ] );
    
    }
    

    output:

      name: Bob
    weight: 90 kg
    height: 1.8 m
    

提交回复
热议问题