Rust Fundamentals · 15 XP Pro

Methods

Methods are functions attached to a type, defined inside an impl block. Their first parameter is the instance, and it says how the method uses it:

  • &self borrows the value to read it,
  • &mut self borrows it to change it,
  • self takes ownership (less common).

You call a method with dot syntax, and Rust inserts the borrow for you:

pub struct Lamp { pub on: bool }

impl Lamp {
    pub fn is_on(&self) -> bool { self.on }
    pub fn toggle(&mut self) { self.on = !self.on; }
}

let mut l = Lamp { on: false };
l.toggle();
assert!(l.is_on());

Methods used from outside the crate need pub, and the variable must be mut to call a &mut self method.

Your task

The struct is already in the starter. Fill in the impl Rectangle block with three pub methods:

  • area(&self) -> u32 returns width * height.
  • is_square(&self) -> bool is true when width equals height.
  • scale(&mut self, factor: u32) multiplies both width and height by factor.

Next lesson →

Sign in to run your code. It's free.