Methods
A method is a function that belongs to a type. You call it with a dot: rect.area().
impl blocks
Methods live in an impl block for the type. Inside it, Self means the type itself.
struct Rect { w: u32, h: u32 }impl Rect { fn area(&self) -> u32 { self.w * self.h }}Inside a method, read fields through self, like self.w. A plain w would not work.
&self
&self borrows the value to read it. The caller keeps ownership, so the value can be used again after the call. Most methods that only look at a value use &self.
&mut self
&mut self borrows the value so the method can change it. The variable must be declared with mut, or the call fails with E0596.
impl Rect { fn grow(&mut self) { self.w += 1; }}let mut r = Rect { w: 2, h: 3 };r.grow(); // r.w is now 3self
A plain self takes ownership of the value. After the call, the old variable can't be used (E0382). Use it when a method turns the value into something else.
Associated functions
A function in an impl block with no self is an associated function. Call it on the type with ::, not on a value with a dot. new is the usual name for one that makes a value.
impl Rect { fn square(n: u32) -> Self { Self { w: n, h: n } }}let s = Rect::square(4);Remember
&selfreads,&mut selfchanges,selftakes.- A
&mut selfmethod needs amutvariable. - No
selfmeans you call it asType::name().