RRust By Example
beginnerBasics

Methods with impl

Define methods on structs using impl blocks.

Methods with impl

Define methods on structs using impl blocks.

Difficulty

Beginner

Code

rust
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 is_square(&self) -> bool {
        (self.width - self.height).abs() < f64::EPSILON
    }
}

fn main() {
    let rect = Rectangle::new(10.0, 5.0);
    println!("area: {}", rect.area());
    println!("square: {}", rect.is_square());

    let sq = Rectangle::new(4.0, 4.0);
    println!("square: {}", sq.is_square());
}

Explanation

Methods defined in impl blocks. &self borrows the instance.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the basics category to build a complete understanding of this topic.

More Basics Examples