Adding Functionality with Methods

Adding Functionality with Methods

Hello! In this lesson, we will explore how to add functionality to your structs using methods in Rust. Just as you use functions to encapsulate behavior in your programs, methods allow you to encapsulate behavior within a struct. This lesson will cover defining methods, creating constructors, and using mutable methods to add functionality to structs.

Let's get started!

What are Methods?

Methods in Rust are similar to functions, but they are associated with an instance of a struct and can operate on its data. Think of methods as actions that instances of structs can perform. Let's use a Rectangle struct as an analogy to understand this concept better.

Imagine we have a Rectangle struct, and we want this rectangle to perform certain actions, such as calculating its area or changing its dimensions. Methods allow us to define these actions directly so the rectangle "knows" how to perform these actions on its own.

Defining Methods for Structs

In Rust, methods are defined within an impl block, connecting them to a specific struct. This enables us to associate behavior with the struct. The first parameter of a method must always be &self. The self keyword refers to the instance of the struct. We use & to prevent the method from taking ownership of the instance. After defining a method, call it using dot syntax on the desired instance of the struct. The instance of the struct automatically gets passed as the self parameter. Let's take a look:

// Define a struct
struct Rectangle {
    width: f32,
    height: f32,
}

// Implement methods for the struct
impl Rectangle {

    // Method to calculate the area
    fn area(&self) -> f32 {
        self.width * self.height
    }
}

fn main() {
    // Create an instance of Rectangle
    let rect = Rectangle {
        width: 30.5,
        height: 50.1,
    };

    // Call the area method
    let rect_area = rect.area();
    println!("Area: {}", rect_area); // Prints: Area: 1528.0499
}

In this example:

  • We defined a struct named Rectangle with two fields: width and height, both of type f32.
  • Inside the impl block, we defined a method area that borrows the instance of the struct using &self. This method calculates and returns the area of the rectangle.
  • We then created an instance of Rectangle, called rect
  • We use rect.area() to call the area method. rect automatically gets passed as the self parameter.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal