8.12 Method Syntax and Associated Functions
Methods are functions associated with a type, defined within an impl
block.
8.12.1 Defining Methods
struct Rectangle { width: u32, height: u32, } impl Rectangle { // Associated function (constructor) fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height } } // Method that borrows self immutably fn area(&self) -> u32 { self.width * self.height } // Method that borrows self mutably fn set_width(&mut self, width: u32) { self.width = width; } } fn main() { let mut rect = Rectangle::new(10, 20); println!("Area: {}", rect.area()); rect.set_width(15); println!("New area: {}", rect.area()); }
- Associated Functions: Functions like
new
that are associated with a type but don't takeself
as a parameter. - Methods: Functions that have
self
as a parameter, allowing access to the instance's data.
8.12.2 Method Calls
-
Use the dot syntax to call methods:
instance.method()
. -
The first parameter of a method is
self
, which can be:&self
: Immutable borrow of the instance.&mut self
: Mutable borrow of the instance.self
: Takes ownership of the instance.
Methods and associated functions will be covered in more detail when we explore Rust's struct type in a later chapter.