summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs')
-rw-r--r--rust/theBook/chapter-5-using-struct-to-structure-related-data/method/src/main.rs54
1 files changed, 54 insertions, 0 deletions
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);
+}