Logo

Developer learning path

Rust

Struct Methods in Rust

Struct Methods

17

#description

In Rust, a struct is a composite data type that groups together zero or more values with different types into a single object. Structs in Rust have associated methods, which can be used to perform operations on the data stored inside the struct.

Struct methods are similar to functions in Rust, but they are associated with a specific struct type and can only be called on instances of that type. Struct methods can take parameters just like regular functions, but the first parameter is always a reference to an instance of the struct on which the method is being called.

Here's an example of a struct in Rust with a method:

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

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
                  

In this example, we define a struct Rectangle with two fields: width and height. We then define a method area for the Rectangle struct, which calculates and returns the area of the rectangle.

The impl keyword is used to implement the methods for the Rectangle struct. The &self parameter is a reference to an instance of the Rectangle struct, which allows us to access its fields and perform operations on them.

We can use the area method on an instance of the Rectangle struct like this:

                    
let rect = Rectangle { width: 10, height: 20 };
let area = rect.area();
println!("The area of the rectangle is {}", area);
                  

This will output:

                    
The area of the rectangle is 200
                  

Struct methods are a powerful feature in Rust that allow us to encapsulate behavior with our data and create more expressive and reusable code.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.