Reputation: 11
I started learning macros in Rust. I decided to practice a little and write a simple macro for hashmap. If call the macro this way, then everything works
let hashmap = hashmap!{ 1 => String::from("1"), 2 => String::from("2") };
But I wanted to add the ability to support an optional comma at the end.
For example, so that I can call a macro like this
let hashmap = hashmap!{ 1 => String::from("1"), };
My macro looks like this
macro_rules! hashmap {
($($key:expr => $val:expr),*) => {
{
let mut map = ::std::collections::HashMap::new();
$(
map.insert($key, $val);
)*
map
}
}
}
I was trying to add something like ,?
or this (,)?
, but it doesn't work and outputs an error
Upvotes: 1
Views: 37