Structs & implementation Methods

🦀 Rust Lesson 10 Intermediate

Rust structures define custom data types. Implementation blocks (impl) bind methods and associated functions to these structures.

1 Struct Declarations & self References

Rust structures define fields. Methods are declared inside a separate **`impl` block**. Methods accept self references to access struct properties:

  • `&self`: Borrows the struct immutably (read-only access).
  • `&mut self`: Borrows the struct mutably (allows field modifications).
  • `self`: Takes ownership of the struct (consumes the object).
2 Structs & Methods Code

Let's run a program declaring structures and binding implementation methods:

Rust — Structs & Methods ▶ Run Code
struct Student {
    name: String,
    grade: f32,
}

// Implementation block binding methods to Student
impl Student {
    // Associated function (constructor, doesn't take self)
    fn new(name: &str, grade: f32) -> Student {
        Student {
            name: name.to_string(),
            grade,
        }
    }

    // Method borrowing self reference
    fn print_info(&self) {
        println!("Student: {}, Grade: {}", self.name, self.grade);
    }
}

fn main() {
    // Instantiate using constructor
    let s = Student::new("Alice", 3.8);
    s.print_info();
}
3 Code Challenge
Challenge: Write a struct called `Rectangle` with fields `width` and `height`. Implement methods to calculate its area and check if it is a square, and test them in `main()`.