Skip to Content
Rust Programming By Example
book

Rust Programming By Example

by Guillaume Gomez, Antoni Boucher
January 2018
Beginner to intermediate
454 pages
10h 8m
English
Packt Publishing
Content preview from Rust Programming By Example

Repetitions

In a macro pattern, it is also possible to match against an unlimited number of patterns, using the repetition operators + and *. They behave exactly like the same operators in regular expressions:

  • + matches 1 or more times.
  • * matches 0, 1, or more times.

Let's write a very useful macro, a macro to provide syntactic sugar to create HashMaps:

Note: A HashMap is a data structure from Rust's standard library that maps keys to values.

macro_rules! hash {
    ($( $key:expr => $value:expr ),*) => {{
        let mut hashmap = ::std::collections::HashMap::new();
        $(hashmap.insert($key, $value);)*
        hashmap
    }};
}

As we can see, we use the * operator here. The comma before it specify the separator token: this token must be present between each occurrence ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Rust Programming Cookbook

Rust Programming Cookbook

Claus Matzinger
Rust Web Programming

Rust Web Programming

Maxwell Flitton

Publisher Resources

ISBN: 9781788390637Supplemental Content