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() {
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 {
// returns a boolean
if rhs == 0 {
return false;
}
return lhs % rhs == 0;
struct Rectangle {
width: u32,
height: u32,
}
fn fizzbuzz(n: u32) -> () {
// this returns nothing, so '()'
match (is_divisible_by(n, 3), is_divisible_by(n, 5)) {
(true, true) => println!("fizzbuzz"),
(true, false) => println!("fizz"),
(false, true) => println!("buzz"),
(false, false) => println!("{n}"),
impl Rectangle {
fn area(&self) -> u32 {
return self.width * self.height;
}
}
fn fizzbuzz_to(n: u32) {
// like above, but you can omit the '()'
for n in 1..=n {
fizzbuzz(n);
fn inc_width(&mut self, delta: u32) {
self.width += delta;
}
}

Binary file not shown.