Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mastering Rust. - Second Edition

You're reading from  Mastering Rust. - Second Edition

Product type Book
Published in Jan 2019
Publisher Packt
ISBN-13 9781789346572
Pages 554 pages
Edition 2nd Edition
Languages
Author (1):
Rahul Sharma Rahul Sharma
Profile icon Rahul Sharma

Table of Contents (19) Chapters

Preface 1. Getting Started with Rust 2. Managing Projects with Cargo 3. Tests, Documentation, and Benchmarks 4. Types, Generics, and Traits 5. Memory Management and Safety 6. Error Handling 7. Advanced Concepts 8. Concurrency 9. Metaprogramming with Macros 10. Unsafe Rust and Foreign Function Interfaces 11. Logging 12. Network Programming in Rust 13. Building Web Applications with Rust 14. Interacting with Databases in Rust 15. Rust on the Web with WebAssembly 16. Building Desktop Applications with Rust 17. Debugging 18. Other Books You May Enjoy

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 chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}