>

Implementation

The impl, implementation block, allows attaching functions to structures.

I’ve written about structures, here.

The Point

For my example code, I’ll have a simple 2 dimentional Point.

1
2
3
4
struct Point {
    X: i64,
    Y: i64,
}

Adding functionality

Now to add some functions to the Point.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
impl Point {
    fn add(&mut self, v i64) -> *Point {
        self.X += v;
        self.Y += v;
        self
    }
    fn equal(&self, o *Point) -> bool {
        self.X == o.X && self.Y == o.Y
    }
}

These add 2 functions that will be appart of the Point structure.

This means all Point structure instances will have add and equal functions.

Using this functionality

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn main() {
    let p1 = Point{X: 2, Y: 0};
    p1.add(3);
    println!("({}, {})", p1.X, p1.Y);
    if p1.equal(&Point{X: 5, Y: 3}) {
        println!("(5, 3) = true");
    } else {
        println!("(5, 3) != ({}, {})", p1.X, p1.Y);
    }
}

2023-11-01