Creating a new function

Here is a macro, create_fn, to create a new function at compile time:

macro_rules! create_fn { 
    ($fname:ident) => ( 
        fn $fname() { 
        println!("Called the function {:?}()", stringify!($fname)) 
        } 
    ) 
} 

stringify! is a built-in macro that makes a string from its argument.

Now we can invoke this macro with create_fn!(fn1);. This statement does not sit inside main() or another function; it is transformed during compilation into the function definition. Then a normal call to that function fn1() will call it, here printing:

Called the function "fn1"().