In this tutorial, you’ll learn how to add behavior to your structs by implementing methods.
What Are Methods? #
- A method is a function defined inside the context of a struct.
- Unlike regular functions, methods take
self(the instance of the struct) as their first parameter. - This allows methods to act on the data inside the struct.
Defining Methods with impl #
We use the impl keyword to add methods to a struct:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}Code language: Rust (rust)In this example:
impl Rectangle { ... }means “implement methods forRectangle.”fn area(&self)defines a method calledarea.&selfis short forself: &Self, meaning a reference to the struct instance.
Calling Methods #
fn main() {
let rect = Rectangle { width: 30, height: 50 };
println!("The area is {} square pixels.", rect.area());
}
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
Code language: Rust (rust)Notice how we call it with dot syntax: rect.area().
Methods with Parameters #
You can also pass extra arguments:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle { width: 50, height: 50 };
let rect2 = Rectangle { width: 30, height: 40 };
println!("rect1 can hold rect2? {}", rect1.can_hold(&rect2));
}
Code language: Rust (rust)Here, can_hold checks if one rectangle can fit inside another.
Associated Functions (No self) #
Sometimes you want functions related to the struct, but not tied to a specific instance. These are called associated functions:
impl Rectangle {
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
fn main() {
let sq = Rectangle::square(20);
println!("Square area: {}", sq.area());
}
Code language: Rust (rust)Call them with :: syntax (e.g., Rectangle::square(20)). This feels a lot like a constructor in other languages.
Multiple impl Blocks #
You can split methods into different impl blocks:
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
impl Rectangle {
fn perimeter(&self) -> u32 {
2 * (self.width + self.height)
}
}
Code language: Rust (rust)Rust allows this for organization and readability.
Summary #
- Define methods inside an
implblock. - Methods take
&self,&mut self, orselfdepending on borrowing/ownership needs. - Use dot syntax to call methods.
- Associated functions (without
self) are called with::. - Multiple
implblocks are allowed.
Was this Helpful ?