Created
November 11, 2018 01:58
-
-
Save ccutch/17883201e50946e6b1e19a21bc05453b to your computer and use it in GitHub Desktop.
Making a quick macro to easily write functions for enums that simply match an variant to a defined return type
This file contains 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
// Example enum Material | |
pub enum Material { | |
Grass, | |
Sand, | |
Rock, | |
Water, | |
} | |
// match_prop macro | |
macro_rules! match_prop { | |
// usage with normal return type | |
($s:ident.$p:ident() -> $t:tt, $($e:ident => $r:expr,)+) => { | |
impl $s { | |
fn $p(&self) -> $t { | |
match self { | |
$($s::$e => $r,)* | |
} | |
} | |
} | |
}; | |
// usage with borrow return, using self lifetime | |
($s:ident.$p:ident() -> &$t:tt, $($e:ident => $r:expr,)+) => { | |
impl $s { | |
fn $p<'a>(&'a self) -> &'a $t { | |
match self { | |
$($s::$e => $r,)* | |
} | |
} | |
} | |
} | |
} | |
// Usage with normal return type | |
match_prop![Material.identifier() -> u16, | |
Grass => 0x01, | |
Sand => 0x02, | |
Rock => 0x03, | |
Water => 0x04, | |
]; | |
// Usage with borrow return type | |
match_prop![Material.string_name() -> &str, | |
Grass => "grass", | |
Sand => "sand", | |
Rock => "rock", | |
Water => "water", | |
]; | |
fn main() { | |
// Quick test | |
let material = Material::Grass; | |
assert_eq!(material.identifier(), 0x01); | |
assert_eq!(material.string_name(), "grass"); | |
// Print for debugging | |
println!("Identifier: {:?}", Material::Rock.identifier()); | |
println!("String name: {:?}", Material::Rock.string_name()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment