Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Last active May 27, 2018 20:58
Show Gist options
  • Save ElectricCoffee/e211a7d956a351dc1ea055a7852e9d2b to your computer and use it in GitHub Desktop.
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
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") };
}
@ElectricCoffee
Copy link
Author

Link to the playground [here]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment