Default values for function parameters


#1

Hi,

Is there a way to have default params to functions, not using enums?

Doubt:

Should the parameters be always passed in an order?

Say I have a function

fn part1(points: u32, mut tf: f64, dt: f64) {
// code follows here
}

In order to call it, should we follow the parameter order or can we initialise arguments
randomly. In python

part1(tf=3., dt=1e-1, points=30)

How can we call this in rust?


#2

Rust doesn’t have this ability, but you can track the issue here:


#3

A verbose option is the builder pattern:

struct Part1 {
    points: u32,
    tf: f64,
    dt: f64
}

impl Part1 {
    fn new() -> Part1 {
        Part1 { points: 30_u32, tf: 3_f64, dt: 0.1_f64 }
    }

    fn tf(mut self, tf: f64) -> Self {
        self.tf = tf;
        self
    }
    fn points(mut self, points: u32) -> Self {
        self.points = points;
        self
    }
    fn dt(mut self, dt: f64) -> Self {
        self.dt = dt;
        self
    }
    fn run(self)  {
        // code here
        println!("{:?}", self);
    }
}

Then

Part1::new().points(10_u32).run();
Part1::new().tf(7_f64).dt(15_f64).run();