maplit
maplit copied to clipboard
Allow `:` for hashmaps
We will be very grateful. Little stylistic changes can have a big impact on workflows.
This will help transition users from other languages, including myself, since this is the syntax in almost every language that supports literals—Go, Python, JavaScript, Ruby.
The implementation is tricky. This is already workable:
macro_rules! map{
( $($key:tt : $val:expr),* $(,)? ) =>{{
#[allow(unused_mut)]
let mut map = ::std::collections::HashMap::with_capacity(hashmap!(@count $($key),* ));
$(
#[allow(unused_parens)]
let _ = map.insert($key, $val);
)*
map
}};
(@replace $_t:tt $e:expr ) => { $e };
(@count $($t:tt)*) => { <[()]>::len(&[$( map!(@replace $t ()) ),*]) }
}
let map = map!{ 1: "one", 2: "two" };
Handling complex expressions probably requires procedural macros.
h/t https://stackoverflow.com/a/71541479/13349653