CodeBlanks Logo Icon CodeBlanks

Summary - Methods

Combine impl, &self and &mut self to compute a Rectangle's area.

Methods summary

An impl Type { ... } block attaches behaviour to a type. &self reads, &mut self modifies, self consumes. Functions that don't take self are associated functions, called with Type::name(); the constructor convention is new. In a dot call Rust adds the needed &/&mut itself. A type can have several impl blocks.

When to use a method?

If the operation concerns the type itself and mostly works on a single instance, write a method. If it produces a new instance, write an associated function (new, from_*, with_*). Getters can have the same name as the field. Methods also make code read as "object.action()", which helps autocompletion.

Practice Point type

For Nokta { x: f64, y: f64 }, write new, fn uzaklik(&self, o: &Nokta) -> f64 (Pythagoras, sqrt) and fn hareket(&mut self, dx: f64, dy: f64). With a = (0, 0) and b = (3, 4): take the distance, then do a.hareket(3.0, 0.0), take it again and print both results.

Starter code

main.rs
struct Nokta {
    x: f64,
    y: f64,
}

fn main() {
    // buraya yaz
}

Sample solution

main.rs
struct Nokta {
    x: f64,
    y: f64,
}

impl Nokta {
    fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
    fn uzaklik(&self, o: &Nokta) -> f64 {
        ((self.x - o.x).powi(2) + (self.y - o.y).powi(2)).sqrt()
    }
    fn hareket(&mut self, dx: f64, dy: f64) {
        self.x += dx;
        self.y += dy;
    }
}

fn main() {
    let mut a = Nokta::new(0.0, 0.0);
    let b = Nokta::new(3.0, 4.0);
    let d1 = a.uzaklik(&b);
    a.hareket(3.0, 0.0);
    let d2 = a.uzaklik(&b);
    println!("{} {}", d1, d2);
}

Expected output

5 4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For <code>fn uzaklik(&amp;self, o: &amp;Nokta) -&gt; f64</code>, which call is correct?

  • a.uzaklik(b)
  • Nokta::uzaklik(b)
  • uzaklik(a, b)
  • a.uzaklik(&b) Correct answer

Explanation: self is borrowed from a automatically; the second parameter is passed explicitly as &b.

2 Constructor return

Question
fn new(x: f64, y: f64) -> ____ {
    Self { x, y }
}
Answer
fn new(x: f64, y: f64) -> Self {
    Self { x, y }
}

Explanation: A constructor returns a new instance of the type, that is, Self.

3 Group summary

Term Meaning
impl Nokta { } Behaviour block
&self Read
&mut self Modify
Nokta::new Constructor

All lessons in Beginner