How it works...

Macros can use + in the argument list to indicate that an argument may repeat at least once or * to indicate that the argument may repeat zero or more times.

In the recipe, we have a macro named find_min, which has two rules in which the matcher with $(...),+ will match one or more expressions, separated by commas. In the first case, we have ($x:expr), which just executes the expression and returns the output; this will be matched if we pass only one expression to the find_min macro. In the second case, we have ($x:expr, $($y:expr),+). Here, $x is followed by at least one $y, and inside the block, we call the find_min! macro on the tail $y; these values are fed to std::cmp::min, which returns the smallest value from the argument list. On the second call, it would execute the first case of the macro and return the expression.

In the main function, we run the following cases and print the results:

  • find_min!(1u32): This will execute the first case and return 1
  • find_min!(1u32 + 2 , 2u32): This will go to the second case, where the macro will be called again for the second expression and the min result of those two expressions will be returned, which is 2
  • find_min!(5u32, 2u32 * 3, 4u32): This is similar to the second case, but here the macro will be called two times and the min result of all the expressions will be returned, which is 4 in this case
..................Content has been hidden....................

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