From 93b1c04a218858ecc59b6b8929103695b7b8c2a0 Mon Sep 17 00:00:00 2001 From: Carlos Maiolino Date: Sat, 6 Sep 2025 09:30:14 +0200 Subject: Move rust playground here Signed-off-by: Carlos Maiolino --- rust/chap5/rectangle.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 rust/chap5/rectangle.rs (limited to 'rust/chap5/rectangle.rs') 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)); +} -- cgit v1.2.3