Creating code based on value of macro agrument rust

Viewed 32
macro_rules! retry_put {
($mod_name:ident, $data_type:ty) => {{
    fn $mod_name() {
      // somelike
       if $mod_name == "red" {
       // generate code written here and not the one in else block
         return u8;
       }
       else {
       // generate code written here and not the one in if
         return "string";
       }
     }
   }
  }

I am tring to change the return type based on input basically, if input is true return string else return int.

Or maybe give example for : give example where we are accepting a arguement in macro and if its even calulate factorial of 5 and return it as integer and if the agruement is odd calculate the factoreial of 5 and return it as string. And name of both functions should be same. and logic of calculating 5! should not be repeated.

1 Answers

You can overload a macro like this:

macro_rules! retry_put {
(red, $data_type:ty) => {{
    fn red() {
      return u8;
     }
   }
  }
($mod_name:ident, $data_type:ty) => {{
    fn $mod_name() {
      return "string";
     }
   }
  }
}

See macro_rules!.

Related