Created
December 17, 2024 13:46
-
-
Save leobm/e277b0b7f99fbf9cec3f2545d76f9152 to your computer and use it in GitHub Desktop.
Optional Parameters in Rust, different methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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