Methods

Rust has methods, they are simply functions that are associated with a particular type. The first argument of a method is an instance of the type it is associated with:

  1. struct Rectangle {
  2. width: u32,
  3. height: u32,
  4. }
  5. impl Rectangle {
  6. fn area(&self) -> u32 {
  7. self.width * self.height
  8. }
  9. fn inc_width(&mut self, delta: u32) {
  10. self.width += delta;
  11. }
  12. }
  13. fn main() {
  14. let mut rect = Rectangle { width: 10, height: 5 };
  15. println!("old area: {}", rect.area());
  16. rect.inc_width(5);
  17. println!("new area: {}", rect.area());
  18. }
  • We will look much more at methods in today’s exercise and in tomorrow’s class.