Implementing Methods with impl

Methods are functions defined within the context of a struct using the impl block.

Defining Methods

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

Calling Methods

let rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area());

self refers to the instance of the struct. Use &self to borrow the instance immutably.

← PrevNext →