Reader small image

You're reading from  Mastering Rust. - Second Edition

Product typeBook
Published inJan 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789346572
Edition2nd Edition
Languages
Right arrow
Author (1)
Rahul Sharma
Rahul Sharma
author image
Rahul Sharma

Rahul Sharma is passionately curious about teaching programming. He has been writing software for the last two years. He got started with Rust with his work on Servo, a browser engine by Mozilla Research as part of his GSoC project. At present, he works at AtherEnergy, where he is building resilient cloud infrastructure for smart scooters. His interests include systems programming, distributed systems, compilers and type theory. He is also an occasional contributor to the Rust language and does mentoring of interns on the Servo project by Mozilla.
Read more about Rahul Sharma

Right arrow

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

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Mastering Rust. - Second Edition
Published in: Jan 2019Publisher: PacktISBN-13: 9781789346572

Author (1)

author image
Rahul Sharma

Rahul Sharma is passionately curious about teaching programming. He has been writing software for the last two years. He got started with Rust with his work on Servo, a browser engine by Mozilla Research as part of his GSoC project. At present, he works at AtherEnergy, where he is building resilient cloud infrastructure for smart scooters. His interests include systems programming, distributed systems, compilers and type theory. He is also an occasional contributor to the Rust language and does mentoring of interns on the Servo project by Mozilla.
Read more about Rahul Sharma