Default arguments

on 2016-05-20

For most languages in pseudo code this gives something like that:

def my_func(mandatory, default=42)

This is the case for C++, PHP, Ruby, Python and others I forgot to mention.

In C no, but there are some tricks of course with macro's or struct's as option.

In Lua there is no optional/default arguments, so common way is to check the value and set it on the function:

function my_func(mandatory, optional)
    optional = optional or 42
    print(optional)
end

In JavaScript it is like in Lua, but more ugly:

function my_func(mandatory, optional) {
    if (typeof(optional) === 'undefined')
        optional = 42;
    console.log(optional);
}

In Rust its like in C, no (in current stable 1.8, but there is a RFC). Current way to do this is by using a struct/enum and implement Default for it with std::default::Default trait.

use std::default::Default;
use time::now_utc;

pub struct JobOpts {
    pub queue: String,
    pub created_at: i64,
}

impl Default for JobOpts {
    fn default() -> JobOpts {
        JobOpts {
            queue: "default".to_string(),
            created_at: now_utc().to_timespec().sec,
        }
    }
}

impl Job {
    pub fn new(class: String, opts: JobOpts) -> Job {
        Job {
            class: class,
            queue: opts.queue,
            created_at: opts.created_at,
        }
    }
}

To pass default option, you have to pass Default::default() because there is no default argument in Rust :troll:.

Job::new("MyClass".to_string(), Default::default());

To change default option:

let job_opts = JobOpts {
    queue: "42".to_string(),
    ..Default::default()
};
Job::new("MyClass".to_string(), job_opts);