Methods with impl
impl blocks add methods. &self reads, &mut self changes and no self makes an associated function.
Example
struct Rect { w: u32, h: u32 }
impl Rect {
fn new(w: u32, h: u32) -> Self { Rect { w, h } }
fn area(&self) -> u32 { self.w * self.h }
fn grow(&mut self) { self.w *= 2; }
}
fn main() {
let mut r = Rect::new(3, 4);
println!("{}", r.area());
r.grow();
println!("{}", r.area());
}Result
12 24
Exercise
Method receiver.
fn area(self)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.