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:
&selfborrows the value to read it,&mut selfborrows it to change it,selftakes 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) -> u32returnswidth * height.is_square(&self) -> boolistruewhen width equals height.scale(&mut self, factor: u32)multiplies both width and height byfactor.