Rustlings: macros3.rs #Issue78 — Macros in Rust
Rustlings Challenge: macros3.rs Solution Walkthrough

This is the Seventy-eighth (78th) 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 macros3.rs.
Previous challenge #Issue 77
Challenge:
// macros3.rs
//
// Make me compile, without taking the macro out of the module!
//
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
mod macros {
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
}
fn main() {
my_macro!();
}Explanation:
Macros defined in a module are not visible outside that module by default. To make the code compile, we need to make the macro my_macro accessible from the main module. You can do this by using the #[macro_export] attribute on the module that contains the macro definition.
Solution:
mod macros {
#[macro_export]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
}
fn main() {
my_macro!();
}In our solution code:
- We add
#[macro_export]to the macro definition to indicate that it should be exported and accessible from other modules. - In the main function, we access the macro using the module path
macros::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!
