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

Repetitions in macros

Apart from token tree types, we also need a way to repeatedly generate certain parts of our code. One of the practical examples from the standard library is the vec![] macro, which relies on repetition to give an illusion of variadic arguments, and allows you to create Vecs in any of the following manners:

vec![1, 2, 3];
vec![9, 8, 7, 6, 5, 4];

Let's see how vec! does this. Here's vec's macro_rules! definition from the standard library:

macro_rules! vec {
($elem:expr; $n:expr) => (
$crate::vec::from_elem($elem, $n)
);
($($x:expr),*) => (
<[_]>::into_vec(box [$($x),*])
);
($($x:expr,)*) => (vec![$($x),*])
}

By ignoring the details to the right of => and focusing on the last two matching rules on the left-hand side, we can see something new in these rules:

($($x:expr),*)
($($x:expr,)*)

These are repeating...

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