Logo

dev-resources.site

for different kinds of informations.

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

Published at
1/12/2024
Categories
rust
100daysofcode
learning
self
Author
aniket_botre
Categories
4 categories in total
rust
open
100daysofcode
open
learning
open
self
open
Author
12 person written this
aniket_botre
open
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

self Article's
30 articles in total
Favicon
Self hosted supabase setup with Authelia and Caddy
Favicon
Microsoft Certification Courses
Favicon
Hello World!
Favicon
Embracing Self-Care: Your Path to Wellness
Favicon
self, Self, and Self.self in Swift
Favicon
Day 14: Rust's Symphony of Generics and Traits – Crafting Code for the Real World πŸŒπŸš€
Favicon
Day 13: Rust Enums – Unleashing the Power of Variants! πŸ’ͺπŸ¦€
Favicon
Day 12: Navigating the Rustic Terrain of Struct Methods 🏞️
Favicon
Day 10: Rustic Riddles - Unleashing the Number Guessing Game 🎲
Favicon
Day 7: Unleashing Functions in Rust πŸš€
Favicon
Day 5: Mastering Rust's Conditionals and Match Expressions
Favicon
Mindful Practices that help me get out of my own head and my way
Favicon
What Weightlifting Has Taught Me About Systems Engineering
Favicon
The Mindset Shift that Transform My Long-Term Outlook
Favicon
Embracing the Power of Being Second
Favicon
The 9-to-5 Scholar: Completing MIT OCW CSE with a Full time Job
Favicon
2022 retro, and what's up
Favicon
Find Prime Number in C++
Favicon
Top 6 Sites para Encontrar, Gerar, Criar e Compartilhar Memes
Favicon
Day-2 of Machine Learning
Favicon
The worst piece of life advice I ever received
Favicon
Como saber e validar o dΓ­gito verificador do RG (Registro Geral)
Favicon
Como descobrir qual a espΓ©cie de planta por foto?
Favicon
Orientação a objetos baseada em protótipos parte 2
Favicon
Top ways to become a self taught developer
Favicon
Why Polywork?
Favicon
Become a better front-end developer
Favicon
"Sophie's World in Ruby"
Favicon
Melhores Sites para Encontrar EstΓ‘gios do Brasil
Favicon
Melhores Sites de Emprego do Brasil

Featured ones: