Method Syntax

Methods are similar to functions: we declare them with the fn keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. Methods are defined within an impl (impl…


This content originally appeared on DEV Community and was authored by Daniel

Methods are similar to functions: we declare them with the fn keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. Methods are defined within an impl (implementation) block, and they can either be associated functions (called with the :: syntax) or instance methods (called with the . syntax).
Here is how you define and call a method:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // This is an instance method.
    fn area(&self) -> u32 {
        self.width * self.height
    }

    // This is another instance method.
    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width > other.width && self.height > other.height
    }

    // This is an associated function.
    fn square(size: u32) -> Rectangle {
        Rectangle {
            width: size,
            height: size,
        }
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    let rect2 = Rectangle {
        width: 10,
        height: 40,
    };

    let rect3 = Rectangle {
        width: 60,
        height: 45,
    };

    println!("The area of the rectangle is {} square pixels.", rect1.area());

    println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
    println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));

    let square = Rectangle::square(20);
    println!("Square rectangle: {} x {}", square.width, square.height);
}

In the signature for area, we use &self instead of rectangle: &Rectangle. The &self is actually short for self: &Self. Within an impl block, the typeSelf is an alias for the type that the impl block is for. Methods must have a parameter named selfof type Selffor their first parameter, so Rust lets you abbreviate this with only the name selfin the first parameter spot. Note that we still need to use the & in front of the self shorthand to indicate that this method borrows the Self instance, just as in rectangle: &Rectangle. Methods can take ownership of self, borrow selfimmutably, as we’ve done here, or borrow self mutably, just as they can any other parameter.

self, &self, and &mut self

  • self: Consumes the instance. The method takes ownership of the instance, which means the instance will be moved.
  • &self: Borrows the instance immutably. This allows the method to read from the instance without taking ownership.
  • &mut self: Borrows the instance mutably. This allows the method to modify the instance.


This content originally appeared on DEV Community and was authored by Daniel


Print Share Comment Cite Upload Translate Updates
APA

Daniel | Sciencx (2024-07-30T04:00:40+00:00) Method Syntax. Retrieved from https://www.scien.cx/2024/07/30/method-syntax/

MLA
" » Method Syntax." Daniel | Sciencx - Tuesday July 30, 2024, https://www.scien.cx/2024/07/30/method-syntax/
HARVARD
Daniel | Sciencx Tuesday July 30, 2024 » Method Syntax., viewed ,<https://www.scien.cx/2024/07/30/method-syntax/>
VANCOUVER
Daniel | Sciencx - » Method Syntax. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/30/method-syntax/
CHICAGO
" » Method Syntax." Daniel | Sciencx - Accessed . https://www.scien.cx/2024/07/30/method-syntax/
IEEE
" » Method Syntax." Daniel | Sciencx [Online]. Available: https://www.scien.cx/2024/07/30/method-syntax/. [Accessed: ]
rf:citation
» Method Syntax | Daniel | Sciencx | https://www.scien.cx/2024/07/30/method-syntax/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.