Skip to content

Instantly share code, notes, and snippets.

@luqmana
Last active December 21, 2015 00:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luqmana/6219956 to your computer and use it in GitHub Desktop.
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
Copy link
Author

luqmana commented Aug 13, 2013

-> % 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