methods on a struct

This commit is contained in:
Vincent Batts 2023-01-14 16:04:26 -05:00
parent bb36d8fe90
commit f7e268c839
23 changed files with 15 additions and 19 deletions

View file

@ -1,28 +1,24 @@
fn main() { fn main() {
fizzbuzz_to(20); // defined below. No forward declaration needed. let mut rect = Rectangle {
width: 10,
height: 5,
};
println!("old area: {}", rect.area());
rect.inc_width(5);
println!("new area: {}", rect.area());
} }
fn is_divisible_by(lhs: u32, rhs: u32) -> bool { struct Rectangle {
// returns a boolean width: u32,
if rhs == 0 { height: u32,
return false;
}
return lhs % rhs == 0;
} }
fn fizzbuzz(n: u32) -> () { impl Rectangle {
// this returns nothing, so '()' fn area(&self) -> u32 {
match (is_divisible_by(n, 3), is_divisible_by(n, 5)) { return self.width * self.height;
(true, true) => println!("fizzbuzz"),
(true, false) => println!("fizz"),
(false, true) => println!("buzz"),
(false, false) => println!("{n}"),
} }
}
fn fizzbuzz_to(n: u32) { fn inc_width(&mut self, delta: u32) {
// like above, but you can omit the '()' self.width += delta;
for n in 1..=n {
fizzbuzz(n);
} }
} }

Binary file not shown.