Skip to content

Instantly share code, notes, and snippets.

@luqmana
Last active December 21, 2015 00:28
Show Gist options
  • Select an option

  • Save luqmana/6219956 to your computer and use it in GitHub Desktop.

Select an option

Save luqmana/6219956 to your computer and use it in GitHub Desktop.
A macro to easily create and populate hash maps.
#![feature(macro_rules)]
extern crate collections;
use collections::HashMap;
// A macro to easily create and populate hash maps
macro_rules! hashmap(
{ $($key:expr => $value:expr),+ } => {
{
let mut m = HashMap::new();
$(
m.insert($key, $value);
)+
m
}
};
($hm:ident, { $($key:expr => $value:expr),+ } ) => (
{
$(
$hm.insert($key, $value);
)+
}
);
)
fn main() {
// Create a new hashmap
let mut hm = hashmap! {
"a string" => 21,
"another string" => 33
};
// Can also insert into it
// the usual way
hm.insert("and another", 43);
// or also use the macro with
// an existing hashmap
hashmap!(hm, {
"hey, look!" => 56,
"even more" => 77
});
for (k, v) in hm.iter() {
println!("({}, {})", *k, *v);
}
}
@luqmana

luqmana commented Aug 13, 2013

Copy link
Copy Markdown
Author
-> % rust run hash-macro.rs
("another string", 33)
("and another", 43)
("even more", 77)
("a string", 21)
("hey, look!", 56)

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