diff --git a/ch5/method_syntax/src/main.rs b/ch5/method_syntax/src/main.rs index 2d06392..788a64d 100644 --- a/ch5/method_syntax/src/main.rs +++ b/ch5/method_syntax/src/main.rs @@ -16,6 +16,17 @@ impl Rectangle { fn width(&self) -> bool { self.width > 0 } + + fn set_width(&mut self, width: u32) { + self.width = width; + } + + fn max(self, other: Rectangle) -> Rectangle { + Rectangle { + width: self.width.max(other.width), + height: self.height.max(other.height), + } + } } fn main() { @@ -33,6 +44,22 @@ fn main() { println!("rect has a nonzero width; it is: {}", rect1.width); } - // stopped here: - // https://rust-book.cs.brown.edu/ch05-03-method-syntax.html#methods-and-ownership + // need mutable reference to set width + let rect0 = Rectangle { + width: 0, + height: 0, + }; + + println!("{}", rect0.area()); + let other_rect = Rectangle { + width: 1, + height: 1, + }; + let max_rect = rect0.max(other_rect); // can't use rect0 after passing to max + + let mut mut_rect = Rectangle { + width: 0, + height: 0, + }; + mut_rect.set_width(9); }