Rustlings: macros2.rs #Issue77 — Macros in Rust
Rustlings Challenge: macros2.rs Solution Walkthrough

This is the Seventy-seventh (77th) issue of the Rustlings series. In this issue, we provide solutions to Rustlings exercises along with detailed explanations. In this issue we will solve the challenge on macros2.rs.
Previous challenge #Issue 76
Challenge:
// macros2.rs
//
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
my_macro!();
}
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}Explanation:
In Rust, macro expansion order matters, which means that macros must be defined before they are used. This is why our code doesn't compile because the macro has been used before it is defined.
For the code to compile, we need to move our macro definition before it is used.
Solution:
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
my_macro!();
}
You can experiment with the code on Rust Playground.
Resources
Before you go
Thank you for taking the time to read through this challenge. We invite you to share your knowledge of Rust as well. If you found this article valuable, please don’t hesitate to share it with others. Don’t forget to follow the publication and give the article some claps 👏.
Thank you, and we look forward to seeing you for the next challenges!
