DEV Community

Cover image for Day 12: Navigating the Rustic Terrain of Struct Methods 🏞️
Aniket Botre
Aniket Botre

Posted on

Day 12: Navigating the Rustic Terrain of Struct Methods 🏞️

Salutations, fellow Rust enthusiasts! On Day 12 of my #100DaysOfCode Rust journey, let's explore the lush landscapes of struct methods and delve into the enigmatic world of impl.


Framing the Scene: Methods on Structs 🎨

Methods in Rust are functions associated with a specific type, such as a struct, and are defined within a impl block, we declare them with the fn keyword and a name, they can have parameters and a return value. The first parameter of a method is always, which represents the instance of the type on which the method is called.

Method Receivers and Ownership

If you want to write methods in Rust, you need to understand how method receivers work. Method receivers are the first parameters of a method that determine how the method can use and change the data it belongs to. Rust has four kinds of method receivers: &self, &mut self, self, and mut self. Each one has different rules for how the data is borrowed, owned, and mutated by the method. Picking the right method receiver is important for making your code work the way you want and avoiding errors.

Here's a sneak peek:

// Define a struct named `Rectangle`
struct Rectangle {
    width: u32,
    height: u32,
}

// Implementing methods for the `Rectangle` struct
impl Rectangle {
    // Method to calculate the area
    fn calculate_area(&self) -> u32 {
        self.width * self.height
    }

    // Another method to check if one rectangle can hold another
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }
}

// Create instances of the `Rectangle` struct
let rect1 = Rectangle { width: 30, height: 50 };
let rect2 = Rectangle { width: 10, height: 40 };

// Call methods on the instances
let area = rect1.calculate_area();
let can_hold = rect1.can_hold(&rect2);

// Output: area = 1500, can_hold = true
Enter fullscreen mode Exit fullscreen mode

In this picturesque Rust scenario, the Rectangle struct graciously offers methods like calculate_area and can_hold, providing a tailored experience for interacting with rectangles.


Associated Functions

All functions defined within an impl block are called associated functions because they’re associated with the type named after the impl.

They are similar to methods but do not take self as a parameter. They are associated with the struct itself and can be thought of as static methods in other languages.

// Implementing a method for the `Rectangle` struct using `impl`
impl Rectangle {
    // A new method to create a square
    fn create_square(size: u32) -> Rectangle {
        Rectangle { width: size, height: size }
    }
}

// Using the new method to create a square
let square = Rectangle::create_square(20);

// Output: square = Rectangle { width: 20, height: 20 }
Enter fullscreen mode Exit fullscreen mode

Here, the create_square method becomes a beacon of clarity within the impl domain, simplifying the creation of squares. The resulting square instance stands proudly with dimensions 20x20.


Orchestrating Traits with Structs: A Harmonious Sonata 🎡

Rust's trait system is like a musical conductor, guiding shared behaviors across different structs. We'll skip traits for now, but get ready for a tuneful journey in future Rustic pieces.

As we wander through the Rustic terrains of struct methods and related concepts, each line of code paints a vibrant stroke on our coding canvas. Join me on Day 13 for more Rust adventures! Happy coding! πŸ’»πŸŒ„βœ¨

RustLang #Programming #LearningToCode #CodeNewbie #TechJourney #Day12

Top comments (2)

Collapse
 
sdeby profile image
Serge Eby

Aniket, I enjoyed reading your article. Thanks for sharing!

Collapse
 
aniket_botre profile image
Aniket Botre

You are welcome!😊😊