O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Repeating constructs

We just need one additional mechanism for writing our macros: a way to model repeating patterns. We've seen this in the vec! macro before:

vec![1, 2, 3] 

This would create and return a new vector with three elements. Let's see how vec! does it. Here's its macro_rules! definition:

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

Let's ignore the right-hand side and focus on the last two patterns:

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

The repeating pattern matches follow this pattern: $($var:type). There may be any number of string literals sprinkled in there, depending on what you want your macro invocation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required