Commit 7e23900

mo khan <mo@mokhan.ca>
2025-06-03 22:06:08
create a class method
1 parent 456eb97
Changed files (1)
5.3
5.3/src/main.rs
@@ -12,6 +12,13 @@ impl Rectangle {
     fn can_hold(&self, other: &Rectangle) -> bool {
         self.width > other.width && self.height > other.height
     }
+
+    fn square(size: u32) -> Self {
+        Self {
+            width: size,
+            height: size,
+        }
+    }
 }
 
 fn main() {
@@ -27,6 +34,7 @@ fn main() {
         width: 60,
         height: 45,
     };
+    let rect4 = Rectangle::square(10);
 
     println!(
         "The area of the rectangle is {} square pixels.",
@@ -34,4 +42,5 @@ fn main() {
     );
     println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
     println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
+    println!("rect4 is a square: {}", &rect4.area());
 }