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 ...

Get Mastering Rust - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.