LibraryMethods on Structs

Methods on Structs

Learn about Methods on Structs as part of Rust Systems Programming

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

code
impl
(implementation) block. The
code
impl
block specifies which struct the methods are for. The first parameter of a method is always
code
self
, which represents an instance of the struct.
code
self
can be
code
self
(takes ownership),
code
&self
(immutable borrow), or
code
&mut self
(mutable borrow), depending on whether the method needs to modify the struct's data.

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:

  1. self: The method takes ownership of the instance. After the method call, the instance is no longer valid.
  2. &self: The method borrows the instance immutably. It can read the data but not change it.
  3. &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

code
impl
block that do not take
code
self
as their first parameter are called associated functions. These are often used as constructors or factory functions to create new instances of the struct. They are called using the struct's name and the
code
::
syntax (e.g.,
code
StructName::function_name()
).

What is the primary difference between a method and an associated function in Rust?

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:

rust
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// Method that borrows immutably
fn 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

FeatureMethodAssociated Function
First Parameterself, &self, or &mut selfNone
PurposeOperate on struct instance dataCreate struct instances (constructors), utility functions
Calling Syntaxinstance.method_name()StructName::function_name()

Learning Resources

Methods - The Rust Programming Language Book(documentation)

The official Rust book provides a comprehensive explanation of method syntax, including `self`, `&self`, and `&mut self`.

Rust `impl` Keyword Explained(blog)

A clear explanation of the `impl` keyword in Rust, covering how to define methods and associated functions for structs.

Rust Methods and Associated Functions Tutorial(video)

A video tutorial demonstrating the practical application of methods and associated functions with Rust structs.

Rust by Example: Methods(documentation)

Illustrates method syntax and associated functions with runnable code examples.

Understanding `self` in Rust(blog)

A deep dive into the different forms of `self` (`self`, `&self`, `&mut self`) and their implications.

Structs in Rust - GeeksforGeeks(blog)

Covers structs and their associated methods, providing a good overview for beginners.

Rust Programming Language - Methods(documentation)

A concise explanation of methods and associated functions in Rust, with simple examples.

Rust Programming: Methods and Associated Functions(video)

Another video resource explaining the concepts of methods and associated functions in Rust.

Rust Ownership and Borrowing(documentation)

Essential reading for understanding why `&self` and `&mut self` are used in methods.

Rust `impl` Trait(documentation)

The official Rust reference documentation on associated items, including methods and their definitions.