AmitKumarDas / Decisions

Apache License 2.0
10 stars 3 forks source link

Rust: Method can be invoked as a function #132

Open AmitKumarDas opened 5 years ago

AmitKumarDas commented 5 years ago

:nerd_face: &self is implicitly passed as an argument during a method invocation :neckbeard: A defined method can be invoked as a function as well. No extra functional topping. :nerd_face: rectangle.perimeter() === Rectangle::perimeter(&rectangle) :bulb: Do you understand how to invoke mutable methods?

struct Rectangle {
    p1: Point,
    p2: Point,
}

impl Rectangle {
    // This method requires the caller object to be mutable
    // `&mut self` desugars to `self: &mut Self`
    fn translate(&mut self, x: f64, y: f64) {
        self.p1.x += x;
        self.p2.x += x;

        self.p1.y += y;
        self.p2.y += y;
    }
}
fn main() {
    let rectangle = Rectangle {
        // Static methods are called using double colons
        p1: Point::origin(),
        p2: Point::new(3.0, 4.0),
    };

    let mut square = Rectangle {
        p1: Point::origin(),
        p2: Point::new(1.0, 1.0),
    };

    // Error! `rectangle` is immutable, but this method requires a mutable
    // object
    rectangle.translate(1.0, 0.0);

    // Okay! Mutable objects can call mutable methods
    square.translate(1.0, 1.0);
}