Learning Rust
Generic function
We will start with a simple generic function squaring a number.
pub fn square<T>(num: T) -> T {
* num
num }
pub(crate) fn main()
{
let d = 1.5;
let e = square(d);
}
Compiler complains that multiplication T * T
is not defined and we have to add some type traits.
pub fn square<T>(num: T) -> T where T: Mul<Output = T> + Copy {
* num
num }
Linter warns that main is not used GitHub issue 12327.
Generic struct
Let us define a generic point class and compare for equality
struct Point<T>
{
pub x: T,
pub y: T,
}
fn main()
{
let p1 = Point{x: 1.2, y:2.3};
let p2 = Point{x: 1.2, y:2.3};
assert_eq!(p1 == p2, true);
}
The equality operator can be implemented manually by defining the eq
function of the PartialEq
trait. For generic structs the impl block also needs an type parameter impl<T>
and a type specification, which allows the comparison of the fields.
impl<T: PartialEq> PartialEq for Point<T> {
fn eq(&self, other: &Self) -> bool {
self.x == other.x && self.y == other.y
}
}
It is also possible to generate the operators automatically by using the derive
attribute.
#[derive(PartialEq)]
struct Point<T>
Polymorphism
Machine Learning with ort
https://ort.pyke.io/introduction