Last active
May 27, 2018 20:58
-
-
Save ElectricCoffee/e211a7d956a351dc1ea055a7852e9d2b to your computer and use it in GitHub Desktop.
Simple lisp-style cond blocks for chaining if-statements in rust without the boilerplate of writing if else if else if
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
macro_rules! cond { | |
($($e:expr => $body:expr),+, _ => $default:expr) => ( | |
$(if $e { $body } else)+ { $default } | |
); | |
($e:expr => $body:expr) => ( if $e { $body }) | |
} | |
fn main() { | |
let age = 25; | |
cond! { | |
age <= 12 => println!("you're quite young"), | |
age > 12 && age <= 19 => println!("pff, teenagers"), | |
age > 19 && age <= 30 => println!("respectable age, I'd say!"), | |
_ => println!("you're getting old!") | |
}; | |
cond!{ age == 25 => println!("... I don't even know where to start with you") }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link to the playground [here]