Skip to content
Rust

Struct with Methods

Define a Rust struct and implement methods with self and Self.

By EZ4Code Team
structmethodintermediate

Code

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

impl Rectangle {
    fn new(width: f64, height: f64) -> Self {
        Rectangle { width, height }
    }

    fn area(&self) -> f64 {
        self.width * self.height
    }

    fn scale(&self, factor: f64) -> Rectangle {
        Rectangle::new(self.width * factor, self.height * factor)
    }
}

fn main() {
    let r = Rectangle::new(10.0, 5.0);
    println!("Area: {}", r.area());
    let big = r.scale(2.0);
    println!("Big area: {}", big.area());
}

Explanation

Defines a struct and implements methods inside an impl block using self (borrow) and Self (current type). The new function acts as a constructor, while &self methods borrow the instance immutably. Methods can return new instances, enabling fluent transformations like scale.

More Rust Snippets