Google News
logo
Rust - Interview Questions
Explain the rule of using &self, self and &mut self in the declaration method?
In Rust, methods are functions associated with a struct or an enum that allow you to perform operations on instances of those types. When declaring methods, you use different forms of the `self` parameter to define how ownership and mutability are handled within the method. Here's a breakdown of the different forms and their implications:

1. `&self`: This form of the `self` parameter indicates that the method takes an immutable reference to the instance on which it is called. The method can read the instance's data but cannot modify it.

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

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

Usage :
let rect = Rectangle { width: 10, height: 20 };
let area = rect.area();  // No ownership transfer, rect remains accessible​

2. `self`: This form of the `self` parameter indicates that the method takes ownership of the instance. The method can consume the instance, modify it, or transfer ownership to another part of the program.

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

impl Rectangle {
    fn double(self) -> Rectangle {
        Rectangle {
            width: self.width * 2,
            height: self.height * 2,
        }
    }
}​

Usage :
let rect = Rectangle { width: 10, height: 20 };
let doubled_rect = rect.double();  // Ownership transferred, rect is no longer accessible​
3. `&mut self`: This form of the `self` parameter indicates that the method takes a mutable reference to the instance. The method can modify the instance's data.

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

impl Rectangle {
    fn resize(&mut self, new_width: u32, new_height: u32) {
        self.width = new_width;
        self.height = new_height;
    }
}​

Usage :
let mut rect = Rectangle { width: 10, height: 20 };
rect.resize(30, 40);  // Mutable reference, rect's data can be modified​

By using different forms of the `self` parameter, you can control how methods interact with instances of a type. Immutable references (`&self`) allow for read-only access, ownership (`self`) allows for consuming and transferring ownership, and mutable references (`&mut self`) enable modifications to the instance's data.
Advertisement