Book Image

The Complete Rust Programming Reference Guide

By : Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger
Book Image

The Complete Rust Programming Reference Guide

By: Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger

Overview of this book

Rust is a powerful language with a rare combination of safety, speed, and zero-cost abstractions. This Learning Path is filled with clear and simple explanations of its features along with real-world examples, demonstrating how you can build robust, scalable, and reliable programs. You’ll get started with an introduction to Rust data structures, algorithms, and essential language constructs. Next, you will understand how to store data using linked lists, arrays, stacks, and queues. You’ll also learn to implement sorting and searching algorithms, such as Brute Force algorithms, Greedy algorithms, Dynamic Programming, and Backtracking. As you progress, you’ll pick up on using Rust for systems programming, network programming, and the web. You’ll then move on to discover a variety of techniques, right from writing memory-safe code, to building idiomatic Rust libraries, and even advanced macros. By the end of this Learning Path, you’ll be able to implement Rust for enterprise projects, writing better tests and documentation, designing for performance, and creating idiomatic Rust code. This Learning Path includes content from the following Packt products: • Mastering Rust - Second Edition by Rahul Sharma and Vesa Kaihlavirta • Hands-On Data Structures and Algorithms with Rust by Claus Matzinger
Table of Contents (29 chapters)
Title Page
Copyright
About Packt
Contributors
Preface
Index

Creating your first macro with macro_rules!


Let's start with declarative macros first by building one using the macro_rules! macro. Rust already has the println! macro, which is used to print things to the standard output. However, it doesn't have an equivalent macro for reading input from the standard input. To read from the standard input, you have to write something like the following:

let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();

These lines of code can be easily abstracted away with a macro. We'll name our macro scanline!. Here's the code that shows us how we want to use this macro:

// first_macro.rs

fn main() {
    let mut input = String::new();
    scanline!(input);
    println!("{:?}", input);
}

We want to be able to create a String instance and just pass it to scanline!, which handles all the details of reading from standard input. If we compile the preceding code by running rustc first_macro.rs, we get the following error:

error: cannot find macro ...