Default and Optional parameter

How can I create a function that use:

  1. Default parameters
  2. Optional arguments.
1 Like

There is no way to specify default parameter values in Rust, but there is an RFC for it. For now you just have to handle this need ad-hoc in whatever way makes sense for your use case.

Take an Option<Foo>.

2 Likes

Well, the closest we have to this in rust is Options. Default values:

fn foo(possibly_supplied: Option<usize>) {
    let x = possibly_supplied.unwrap_or(20); //Default value is 20
}

And for optional arguments, the above is the closest thing, except you handle None values differently:

fn foo(optionally_supplied: Option<usize>) {
    if let Some(x) = optionally_supplied {
        // A value
    else {
        // No value
    }
}

Unfortunately, you can't do things like you can in other languages (In this case C#):

public static int Foo(int x = 0) => 20 * x;
public static int Foo() => 10;
1 Like

I found this as potential solution, liked to share with the community:

  1. for default, use struct and impl Default
  2. for optional, use macro.

example:

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}
    }
}

macro_rules! five_times {
    ($x:expr) => (5 * $x);
    () => (5);
}

fn main() {
    let s = Sample { c: 23, .. Sample::default() };
    println!("{:?} {:?}", s, five_times!());
    
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.