Skip to content

Instantly share code, notes, and snippets.

@rcook
Created July 21, 2023 23:58
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 rcook/32be3c9aff8202f014a62de4c73e62ca to your computer and use it in GitHub Desktop.
Save rcook/32be3c9aff8202f014a62de4c73e62ca to your computer and use it in GitHub Desktop.
More Rust macros
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