Skip to content

Instantly share code, notes, and snippets.

@leobm
Created December 17, 2024 13:46
Show Gist options
  • Save leobm/e277b0b7f99fbf9cec3f2545d76f9152 to your computer and use it in GitHub Desktop.
Save leobm/e277b0b7f99fbf9cec3f2545d76f9152 to your computer and use it in GitHub Desktop.
Optional Parameters in Rust, different methods
#[allow(dead_code)]
fn f1(a: i32) -> i32 {
a
}
#[allow(dead_code)]
fn f2(a: i32, b: i32) -> i32 {
a+b
}
#[allow(dead_code)]
fn f3(a: i32, b: i32, c: i32) -> i32 {
a+b+c
}
macro_rules! sum3{
($x: expr) => {f1($x)}; //call function f1 when there's one variable
($x: expr, $y: expr) => {f2($x, $y)}; //call f2 when there are two
($x: expr, $y: expr, $z: expr) => {f3($x, $y, $z)}; //call f2 when there are two
}
fn add(a: i32, b: impl Into<Option<i32>>) -> i32 {
a + b.into().unwrap_or(0)
}
macro_rules! sum {
($h:expr) => ($h);
($h:expr, $($t:expr),*) =>
($h + sum!($($t),*));
}
fn main() {
dbg!(add(100,1));
dbg!(sum3!(100,200));
dbg!(sum!(100,200, 10, 20, "2"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment