January 2018
Beginner to intermediate
454 pages
10h 8m
English
Let's write a macro that will simplify the implementation of the traits to overload operators. This macro will have two rules: one for the + and one for the - operators. Here's the first rule of the macro:
macro_rules! op { (+ $_self:ident : $self_type:ty, $other:ident $expr:expr) => { impl ::std::ops::Add for $self_type { type Output = $self_type; fn add($_self, $other: $self_type) -> $self_type { $expr } } }; // …
In this pattern, we use other types of syntactic elements: ident, which is an identifier, and <span>expr, which is an expression. The trait (::std::ops::Add) is fully qualified so that the code using this macro won't need to import the Add trait.
And here's the rest of the macro:
(- $_self:ident : $self_type:ty, ...
Read now
Unlock full access