AmitKumarDas / Decisions

Apache License 2.0
10 stars 3 forks source link

Rust: Methods - What & How #130

Open AmitKumarDas opened 5 years ago

AmitKumarDas commented 5 years ago

:nerd_face: Methods in rust are implemented inside the impl block :nerd_face: Static methods are typically constructors :nerd_face: self is the syntactic sugar for self: Self :hammer: :nerd_face: &self is the syntactic sugar for self: &Self :hammer: :nerd_face: &mut self is the syntactic sugar for self: &mut Self :hammer: :nerd_face: Self is the type of the caller object :bulb: Self refers to Type present in impl Type block

struct Point {
 x i32
 y i32
}

impl Point {
  fn new() Point {
    Point {x:1, y:1} // use of : and , - similar to json
  }
}
impl Rectangle {
    // This is an instance method
    // `&self` is sugar for `self: &Self`, 
    // where `Self` is the type of the caller object
    // In this case `Self` = `Rectangle`
    fn area(&self) -> f64 {
        // `self` gives access to the struct fields via the dot operator
        let Point { x: x1, y: y1 } = self.p1;
        let Point { x: x2, y: y2 } = self.p2;

        // `abs` is a `f64` method that returns the absolute value of the
        // caller
        ((x1 - x2) * (y1 - y2)).abs()
    }
}