rust method examples

Here are a few examples of methods in Rust:

rust method examples

struct Point {
    x: i32,
    y: i32,
}

impl Point {
    fn new(x: i32, y: i32) -> Point {
        Point { x, y }
    }

    fn distance_from_origin(&self) -> f64 {
        let x_squared = f64::from(self.x).powi(2);
        let y_squared = f64::from(self.y).powi(2);
        (x_squared + y_squared).sqrt()
    }

    fn translate(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }
}

The new method is a constructor that creates a new Point instance. The distance_from_origin method calculates the distance of the point from the origin (0, 0). The translate method moves the point by a given amount in the x and y directions.

All of these methods are defined within the impl block for the Point struct. The &self parameter in the first two methods is a reference to the instance of the struct on which the method is being called. The &mut self parameter in the translate method is a mutable reference, which allows the method to modify the fields of the struct.

I hope this helps! Let me know if you have any questions.

 

Leave a Reply

Your email address will not be published. Required fields are marked *