Rust Methods
Learn Rust through interactive, bite-sized lessons. Master memory safety without garbage collection.
Start Rust Journey →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.
Defining Methods
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.
Calling Methods
To call a method, use dot notation on an instance of the struct:
let rect = Rectangle { width: 30, height: 50 };
println!("Area: {}", rect.area());
Self Parameter
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 instance
Multiple Parameters
Methods can take additional parameters beyond self:
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
Associated Functions
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.
Best Practices
- Use methods to encapsulate behavior related to a specific type
- Choose the appropriate self parameter based on whether you need to modify the instance
- Use associated functions for operations that don't require an instance
- Follow Rust's naming conventions: methods that return a boolean often start with "is_" or "has_"
Related Concepts
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.