Methods in Rust are similar to functions but are associated with a specific data type, typically a struct. They provide a way to organize code and implement behavior for custom types, enhancing the object-oriented programming capabilities of Rust.
Methods are defined within an impl
block, which is short for "implementation". Here's the basic syntax:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
In this example, we've defined an area
method for the Rectangle
struct. The &self
parameter is a reference to the instance the method is being called on.
To call a method, use dot notation on an instance of the struct:
let rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area());
Methods can take ownership of self, borrow self immutably, or borrow self mutably. The first parameter of a method determines how it interacts with self:
&self
: borrows the instance immutably&mut self
: borrows the instance mutablyself
: takes ownership of the instanceMethods can take additional parameters beyond self:
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
Functions defined within an impl
block that don't take self
as a parameter are called associated functions. These are often used as constructors:
impl Rectangle {
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
let square = Rectangle::square(3);
Associated functions are called using the struct name and the ::
syntax, as shown above.
To deepen your understanding of Rust methods, explore these related topics:
By mastering methods in Rust, you'll be able to write more organized and efficient code, leveraging the power of Rust's type system and ownership model.