From 9d4f5b661ba8a1ef199755f95c78427bf0a301ca Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 30 Sep 2023 20:05:41 -0400 Subject: [PATCH] Up through fn methods in RBE --- rustbyexample/.gitignore | 9 ++--- rustbyexample/fn.d/methods.rs | 74 +++++++++++++++++++++++++++++++++++ rustbyexample/fn.rs | 29 ++++++++++++++ 3 files changed, 106 insertions(+), 6 deletions(-) create mode 100644 rustbyexample/fn.d/methods.rs create mode 100644 rustbyexample/fn.rs diff --git a/rustbyexample/.gitignore b/rustbyexample/.gitignore index 307d7d8..977aaeb 100644 --- a/rustbyexample/.gitignore +++ b/rustbyexample/.gitignore @@ -1,6 +1,3 @@ -*.d/out -*.d/**/out -expression -hello -primitives -variable_bindings +/out/ +/*.d/out +/*.d/**/out diff --git a/rustbyexample/fn.d/methods.rs b/rustbyexample/fn.d/methods.rs new file mode 100644 index 0000000..6c5b7a1 --- /dev/null +++ b/rustbyexample/fn.d/methods.rs @@ -0,0 +1,74 @@ +struct Point { + x: f64, + y: f64, +} + +impl Point { + fn origin() -> Point { + Point { x: 0.0, y: 0.0 } + } + + fn new(x: f64, y: f64) -> Point { + Point { x: x, y: y } + } +} + +struct Rectangle { + p1: Point, + p2: Point, +} + +impl Rectangle { + fn area(&self) -> f64 { + let Point { x: x1, y: y1 } = self.p1; + let Point { x: x2, y: y2 } = self.p2; + + ((x1 - x2) * (y1 - y2)).abs() + } + + fn perimeter(&self) -> f64 { + let Point { x: x1, y: y1 } = self.p1; + let Point { x: x2, y: y2 } = self.p2; + + 2.0 * ((x1 - x2).abs() + (y1 - y2).abs()) + } + + fn translate(&mut self, x: f64, y: f64) { + self.p1.x += x; + self.p2.x += x; + + self.p1.y += y; + self.p2.y += y; + } +} + +struct Pair(Box, Box); + +impl Pair { + fn destroy(self) { + let Pair(first, second) = self; + + println!("Destroying Pair({}, {})", first, second); + } +} + +fn main() { + let rectangle = Rectangle { + p1: Point::origin(), + p2: Point::new(3.0, 4.0), + }; + + println!("Rectangle perimeter: {}", rectangle.perimeter()); + println!("Rectangle area: {}", rectangle.area()); + + let mut square = Rectangle { + p1: Point::origin(), + p2: Point::new(1.0, 1.0), + }; + + square.translate(1.0, 1.0); + + let pair = Pair(Box::new(1), Box::new(2)); + + pair.destroy(); +} diff --git a/rustbyexample/fn.rs b/rustbyexample/fn.rs new file mode 100644 index 0000000..c1e3faf --- /dev/null +++ b/rustbyexample/fn.rs @@ -0,0 +1,29 @@ +fn main() { + fizzbuzz_to(100); +} + +fn is_divisible_by(lhs: u32, rhs: u32) -> bool { + if rhs == 0 { + return false; + } + + lhs % rhs == 0 +} + +fn fizzbuzz(n: u32) -> () { + if is_divisible_by(n, 15) { + println!("fizzbuzz"); + } else if is_divisible_by(n, 3) { + println!("fizz"); + } else if is_divisible_by(n, 5) { + println!("buzz"); + } else { + println!("{}", n); + } +} + +fn fizzbuzz_to(n: u32) { + for n in 1..=n { + fizzbuzz(n); + } +}