-
Book Overview & Buying
-
Table Of Contents
Rust Web Programming - Third Edition
By :
Metaprogramming can generally be described as a way in which a 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, the Coordinate struct is defined with a single generic parameter, T. This T is a placeholder that can represent any type. When we create an instance of Coordinate, Rust’s compiler replaces T with specific types. In our example:
one uses T as i32three uses T as f62This flexibility allows the Coordinate struct to handle different types of numbers without needing implementations for...