Follow the mentioned steps to implement this recipe:
- Create a file named sample_designator.rs, and open it in your text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Implementing designator
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
- Create a macro named create_function, which accepts a designator as an argument:
macro_rules! create_function {
($func_name:ident) => (
fn $func_name() {
// The `stringify!` macro converts an `ident`
into a string.
println!("You called {:?}()",
stringify!($func_name))
}
)
}
- Call the create_function macro to create two functions, foo and bar:
create_function!(foo);
create_function!(bar);
- Create a macro named print_result:
macro_rules! print_result {
($expression:expr) => (
println!("{:?} = {:?}",
stringify!($expression),
$expression)
)
}
- Define the main function, where we play around with the macros we created:
fn main() {
foo();
bar();
print_result!(1u32 + 1);
// Recall that blocks are expressions too!
print_result!({
let x = 1u32;
x * x + 2 * x - 1
});
}
We will get the following output on successful execution of our code: