Skip to content

Instantly share code, notes, and snippets.

@gonejack
Created September 30, 2021 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonejack/49e0b893e754c466a9dcdb2408074a0e to your computer and use it in GitHub Desktop.
Save gonejack/49e0b893e754c466a9dcdb2408074a0e to your computer and use it in GitHub Desktop.
golang like switch in rust
macro_rules! switch {
($($a:expr => $b:expr;)* _ => $e:expr $(,)?) => {
match () {
$(_ if $a => $b,)*
_ => $e,
}
};
}
fn f1() -> bool {
println!("f1");
true
}
fn f2() -> bool {
println!("f2");
true
}
fn main() {
switch! {
f1() => {
println!("match f1");
};
f2() => {
println!("match f2");
};
_ => {}
}
}
// Output:
// f1
// match f1
@gonejack
Copy link
Author

For gopher who love using switch instead of cascading if else.

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