summaryrefslogtreecommitdiff
path: root/rust/chap5/rectangle.rs
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-09-06 09:30:14 +0200
committerCarlos Maiolino <[email protected]>2025-09-06 09:30:14 +0200
commit93b1c04a218858ecc59b6b8929103695b7b8c2a0 (patch)
tree7ae24ff4b2ef06c8d961f2c908ba8511e1fc995b /rust/chap5/rectangle.rs
parent973e27b243ea7f12b6743894465c67a4a6a87eb2 (diff)
Move rust playground here
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'rust/chap5/rectangle.rs')
-rw-r--r--rust/chap5/rectangle.rs54
1 files changed, 54 insertions, 0 deletions
diff --git a/rust/chap5/rectangle.rs b/rust/chap5/rectangle.rs
new file mode 100644
index 0000000..3b0ab98
--- /dev/null
+++ b/rust/chap5/rectangle.rs
@@ -0,0 +1,54 @@
+#[derive(Debug)]
+struct Rectangle {
+ width: u32,
+ height: u32,
+}
+
+impl Rectangle {
+
+ // First parameter for methods must be named 'self', but the
+ // implementation provides some aliases like:
+ //
+ // self == self: Self
+ // &self == self: &Self
+ //
+ // Note though that 'Self' is just an alias for the type referenced
+ // by the impl{} block. So, here:
+ //
+ // impl Rectangle {}
+ // ^ Self is an alias to Rectangle
+
+ fn can_hold(&self, r: &Rectangle) -> bool {
+ self.width > r.width && self.height > r.height
+ }
+ // Here we can pass just a reference to a struct
+ // Rectangle, no need to transfer ownership
+ fn area(self: &Rectangle) -> u32 {
+ self.width * self.height
+ }
+
+ // Associated functions can be defined without a self parameter
+ // so they function can be namespaced with ::
+ fn square(size: u32) -> Self {
+ Self {
+ width: size,
+ height: size,
+ }
+ }
+}
+
+fn main() {
+ let rect = Rectangle {
+ width: dbg!(5 * 10),
+ height: 3,
+ };
+
+ let sqrt = Rectangle::square(90);
+
+ println!("{rect:#?} Area: {}", rect.area());
+
+ dbg!(&rect);
+ dbg!(&sqrt);
+
+ println!("{}", sqrt.can_hold(&rect));
+}