Implementing Operators Using Macros
TL;DR
When implementing operators for structs, the code gets very long without macros, so I'll summarize how to use macros for this purpose.
Macro Basics
Macro arguments are:
| Meaning | Example | |
|---|---|---|
| block | Block | |
| expr | Expression | 1+1 |
| stmt | Statement | |
| pat | Pattern | |
| ty | Type | |
| ident | Identifier | |
| path | Qualified name | T::deafult |
| tt | Single token tree | Almost anything. Operators too. |
| meta | Attribute contents | cfg(target_os = "windows") |
The ones we'll use this time are ident and tt. The key point is that tt can be used for operator arguments. There was some discussion in RFC#426 about creating a dedicated op argument type, but it doesn't seem to have made progress. For example, you can use operators like this:
This time, we'll consider the following simple struct:
We'll define arithmetic operations between Point<T> and <T>.
For example, the Add implementation looks like this:
Since the code is essentially the same for other arithmetic operations, we want to consolidate them with a macro. Basically, we just need to specify the required trait, the function name required by the trait, and the operator.
I wasn't sure how to use operators in macros, so I wrote this up as a note.