How it works...

In this recipe, we create a macro named Check_Val!, which basically plays the role as a match expression arm, but the matching happens through the Rust syntax trees during compilation time. The common syntax of a pattern is as follows:

( $( $x:expr ),* ) => { ... };

Here, the term pattern refers to the left-hand side of =>, which is known as matcher in Rust.

The $x:expr matcher will match any Rust expression and will bind that to syntax tree to the metavariable $x, any Rust tokens that appear in a matcher must match exactly.

We have two pattern matching cases here: x => $e:expr and y => $e:expr. The metavariable is $e, which is used in macro definitions for operations to be done following the successful pattern matching of a macro rule. When we call Check_Val!(y => 3); in the main function, the output is mode Y:3. Here the second case is passed and the value of $e is the same as that of the arguments passed to the Check_Val! macro in the main function.

If we had called Check-Val!(z => 3); we would have got error: no rules expected the token `z`, as we haven't defined a rule for the token z and surrounding the matcher with $(...),* will match zero or more expressions, separated by commas.
..................Content has been hidden....................

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