Last active
December 21, 2015 00:28
-
-
Save luqmana/6219956 to your computer and use it in GitHub Desktop.
A macro to easily create and populate hash maps.
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
#![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); | |
} | |
} |
Author
luqmana
commented
Aug 13, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment