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