A more involved macro – writing a DSL for HashMap initialization
Armed with the knowledge of repetitions and token tree types, let's build something practical using repetitions in macro_rules!
. In this section, we'll build a crate that exposes a macro that allows you to create HashMaps such as the following:
let my_map = map! { 1 => 2, 2 => 3 };
This is more concise and readable compared to manually calling HashMap::new()
, followed by one or more insert
calls. Let's create a new cargo
project by running cargo new macro_map --lib
with the initial block for macro_rules!
:
// macro_map/lib.rs #[macro_export] macro_rules! map { // todo }
Since we want the users to use our macros, we need to add a #[macro_export]
attribute on this macro definition. Macros are private by default in a module, which is similar to other items. We'll call our macro map!
and since we are building our own syntax to initialize HashMap, we'll go with the k => v
syntax, where k
is the key and v
is the...