Created
July 21, 2023 23:58
-
-
Save rcook/32be3c9aff8202f014a62de4c73e62ca to your computer and use it in GitHub Desktop.
More Rust macros
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
use std::collections::HashMap; | |
macro_rules! from_map { | |
($map: ident, $obj: ident, $field: ident) => { | |
$obj.$field = $map.get(stringify!($field)).unwrap().to_string(); | |
}; | |
($map: ident, $obj: ident, $head: ident, $($tail: ident), +) => { | |
from_map!($map, $obj, $head); | |
from_map!($map, $obj, $($tail), +); | |
}; | |
} | |
#[derive(Debug)] | |
struct Foo { | |
aaa: String, | |
bbb: String, | |
ccc: String, | |
} | |
impl Default for Foo { | |
fn default() -> Self { | |
Self { | |
aaa: String::from("DEFAULT"), | |
bbb: String::from("DEFAULT"), | |
ccc: String::from("DEFAULT"), | |
} | |
} | |
} | |
fn main() { | |
let m = &[("aaa", "AAA"), ("bbb", "BBB"), ("ccc", "CCC")] | |
.into_iter() | |
.collect::<HashMap<_, _>>(); | |
let mut foo = Foo::default(); | |
println!("before={:#?}", foo); | |
{ | |
from_map!(m, foo, aaa, bbb, ccc); | |
} | |
println!("after={:#?}", foo); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment