Rust Programming: Defining Methods

0

Defining methods is the process of creating a function that is associated with a specific type. In Rust, methods are defined within the impl block for the type. The first parameter of a method must always be self, which represents the instance of the type that the method is being called on. For example, the following code defines a method called area on the Rectangle struct:

struct Rectangle {

    width: u32,

    height: u32,

}


impl Rectangle {

    fn area(&self) -> u32 {

        self.width * self.height

    }

}

The area method takes a self parameter, which represents the instance of the Rectangle struct that the method is being called on. The method then multiplies the width and height fields of the struct and returns the result.

To call a method, we use the dot notation. For example, the following code calls the area method on the rect1 variable, which is an instance of the Rectangle struct:

let rect1 = Rectangle {

    width: 30,

    height: 50,

};


println!(

    "The area of the rectangle is {} square pixels.",

    rect1.area()

);

The output of this code is:

The area of the rectangle is 1500 square pixels.

As you can see, defining methods can be a very convenient way to encapsulate functionality related to a specific type. 

Post a Comment

0Comments
Post a Comment (0)