From 3172b239863e1151d85197fdb4ea3e42d421256e Mon Sep 17 00:00:00 2001 From: garhve Date: Mon, 26 Dec 2022 16:52:29 +0800 Subject: finish chapter 5 --- .../method/src/main.rs | 54 ++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs (limited to 'rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs') diff --git a/rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs b/rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs new file mode 100644 index 0000000..6109e00 --- /dev/null +++ b/rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs @@ -0,0 +1,54 @@ +#[derive(Debug)] +struct Rect { + height: u32, + width: u32, +} + +impl Rect { + fn new(size: u32) -> Self { + Self { + height: size, + width: size, + } + } + + fn area(&self) -> u32 { + self.width * self.height + } + + fn can_hold(&self, r2: &Rect) -> bool { + if self.height <= r2.width && self.width <= r2.width { + return false; + } else { + return true; + } + } +} + +fn main() { + let r = Rect { + height: 50, + width: 30, + }; + + println!("The area of the rectangle is {} square pixels.", r.area()); + println!("The r = {:?}",r); + dbg!(&r); // return ownership + + + let r2 = Rect { + height: 40, + width: 10, + }; + + let r3 = Rect { + height: 45, + width: 60, + }; + + println!("Can rect1 hold rect2? {}", r.can_hold(&r2)); + println!("Can rect1 hold rect3? {}", r.can_hold(&r3)); + + let r4 = Rect::new(40); + println!("{:?}", r4); +} -- cgit v1.2.3-70-g09d2