Macros
Macros are a way of writing code that writes other code, which is known as metaprogramming.
Macros can take a variable number of parameters.
To define a macro, we use the
macro_rules!construct.The
#[macro_export]annotation indicates that this macro should be made available whenever the crate in which the macro is defined is brought into scope.We must define macros or bring them into scope before you call them in a file, as opposed to functions you can define anywhere and call anywhere.
References:
macros1.rs
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}
fn main() {
// Fix the macro call by adding `!`.
my_macro!();
}This exercise is simple we just need to add
!when calling the macro.
macros2.rs
This exercise also easy one.
We just need to move the macro definition before the
mainfunction.
macros3.rs
In this exercise we need to export
my_macroso it can be accessible inmainfunction.We can do this by adding
#[macro_export]annotation inmy_macrodefinition.
macros4.rs
In this exercise we only need to add
;for each macro rules statement.
Last updated