Metaprogramming with macros
Metaprogramming can generally be described as a way in which the program can manipulate itself based on certain instructions. Considering the strong typing Rust has, one of the simplest ways in which we can meta program is by using generics. A classic example of demonstrating generics is through coordinates, as follows:
struct Coordinate <T> { x: T, y: T } fn main() { let one = Coordinate{x: 50, y: 50}; let two = Coordinate{x: 500, y: 500}; let three = Coordinate{x: 5.6, y: 5.6}; }
In the preceding snippet, we can see that the Coordinate
struct managed to take in and handle three different types of numbers. We can add even more variance to the Coordinate
struct so we can have two different types of numbers in one struct with the following code:
struct Coordinate <T, X> { x: T, ...