Methods on Structs in Rust
In Rust, methods are functions associated with a specific struct (or enum). They allow you to define behavior that operates on the data contained within an instance of that struct. This is a fundamental concept for object-oriented-like programming in Rust, enabling you to encapsulate data and the operations that act upon it.
Defining Methods
Methods are defined within an
impl
impl
self
self
self
&self
&mut self
Methods are functions tied to structs, defined in `impl` blocks.
Methods are like functions but belong to a struct. They are declared inside an impl
block and always take self
as their first parameter, indicating they operate on an instance of the struct.
The impl
keyword is used to define methods for a struct. For example, if you have a struct named Rectangle
, you would write impl Rectangle { ... }
. Inside this block, you define functions. The first parameter of these functions is conventionally named self
. This self
parameter can be of three types:
self
: The method takes ownership of the instance. After the method call, the instance is no longer valid.&self
: The method borrows the instance immutably. It can read the data but not change it.&mut self
: The method borrows the instance mutably. It can read and change the data.
The choice of self
type depends on the method's purpose and whether it needs to modify the struct's state.
Associated Functions (Static Methods)
Functions defined within an
impl
self
::
StructName::function_name()
Methods take self
(or &self
, &mut self
) as their first parameter, operating on an instance of the struct, while associated functions do not take self
and are often used for creating instances.
Example: Rectangle Area
Consider a Rectangle
struct with width
and height
fields. We can define a method area
that calculates and returns the area of the rectangle. This method will take &self
because it only needs to read the width
and height
values without modifying them. We can also define an associated function square
to create a square rectangle.
Text-based content
Library pages focus on text content
Here's an example demonstrating methods and associated functions:
struct Rectangle {width: u32,height: u32,}impl Rectangle {// Method that borrows immutablyfn area(&self) -> u32 {self.width * self.height}// Method that borrows mutably (example: scaling)fn scale(&mut self, factor: u32) {self.width *= factor;self.height *= factor;}// Associated function (constructor)fn square(size: u32) -> Rectangle {Rectangle { width: size, height: size }}}fn main() {let rect1 = Rectangle { width: 30, height: 50 };println!("The area of the rectangle is {} square pixels.", rect1.area());let mut rect2 = Rectangle::square(20);println!("Initial square area: {}", rect2.area());rect2.scale(2);println!("Scaled square area: {}", rect2.area());}
The area
method uses &self
because it only needs to read the struct's data. The scale
method uses &mut self
because it modifies the struct's data.
Methods vs. Functions
Feature | Method | Associated Function |
---|---|---|
First Parameter | self , &self , or &mut self | None |
Purpose | Operate on struct instance data | Create struct instances (constructors), utility functions |
Calling Syntax | instance.method_name() | StructName::function_name() |
Learning Resources
The official Rust book provides a comprehensive explanation of method syntax, including `self`, `&self`, and `&mut self`.
A clear explanation of the `impl` keyword in Rust, covering how to define methods and associated functions for structs.
A video tutorial demonstrating the practical application of methods and associated functions with Rust structs.
Illustrates method syntax and associated functions with runnable code examples.
A deep dive into the different forms of `self` (`self`, `&self`, `&mut self`) and their implications.
Covers structs and their associated methods, providing a good overview for beginners.
A concise explanation of methods and associated functions in Rust, with simple examples.
Another video resource explaining the concepts of methods and associated functions in Rust.
Essential reading for understanding why `&self` and `&mut self` are used in methods.
The official Rust reference documentation on associated items, including methods and their definitions.