How to do it...

Follow the mentioned steps to implement this recipe:

  1. Create a file named sample_designator.rs, and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Implementing designator
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
  1. 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))
}
)
}
  1. Call the create_function macro to create two functions, foo and bar:
        create_function!(foo);
create_function!(bar);
  1. Create a macro named print_result:
        macro_rules! print_result {
($expression:expr) => (
println!("{:?} = {:?}",
stringify!($expression),
$expression)
)
}
  1. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.165.115