Sage-Code Laboratory
index<--

Rust Methods

Methods are functions bound to structured data types that can be called using dot notation. A method receive automatically first parameter that is called "self" representing a reference to current data object. This is how Rust enable object oriented programming.

Implementation

You can use keyword impl to create methods related to user define struct. This is the way to create object like structures in Rust. So rust has a kind of object oriented behavior but different than C++ or Java. Rust do not have class

Example:

/* declare an object with two attributes */
struct Rectangle {
    width: u32,
    height: u32,
}

/* create an implementation for Rectangle object */
impl Rectangle {
    /* define a method for Rectangle */
    fn area(&self) -> u32 {
        self.width * self.height
    }
    /* define second method for Rectangle */
    fn describe(&self) {
      println!("Rectangle: with={}, height={}",
         self.width, 
         self.height
      )
    }
}

fn main() {
    /* use default constructor of type Rectangle */
    let rect1 = Rectangle { width: 30, height: 50 };

    rect1.describe(); //call a method

    println!(
        "rectangle area is {} square pixels.",
         rect1.area() //call second method
    );
}
Notes:

Homework: Open and run the example online: rust-method


Read next: Modules