WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 13 of 100

What is a method in Rust, and how do you define one for a struct?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, a method is a function that is associated with a particular type, and is defined within the scope of a struct or enum, and can access and modify the state of the struct or enum instance.

You can define a method for a struct in Rust by using the "impl" keyword followed by the name of the struct, and then define the method inside the implementation block. Here is an example:

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

In this example, we define a struct named ‘Rectangle‘, which has two fields, ‘width‘ and ‘height‘, both of which are of type ‘u32‘. We then use the ‘impl‘ keyword to define a method named ‘area‘ for the ‘Rectangle‘ struct. The method takes a reference to ‘self‘ as its only parameter, and returns a value of type ‘u32‘.

Inside the implementation block for ‘Rectangle‘, we define the ‘area‘ method using the ‘fn‘ keyword, and use the ‘self‘ parameter to access the ‘width‘ and ‘height‘ fields of the instance. The method calculates the area of the rectangle by multiplying the width and height fields, and returns the result.

To use the method, we create an instance of the ‘Rectangle‘ struct, and then call the ‘area‘ method on it, like so:

    let rect = Rectangle { width: 10, height: 5 };
    let area = rect.area();

This creates a ‘Rectangle‘ instance with a ‘width‘ of ‘10‘ and a ‘height‘ of ‘5‘, and then calls the ‘area‘ method on it to calculate the area, which is ‘50‘. The result is stored in the ‘area‘ variable.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics