Skip to content
This repository has been archived by the owner on Mar 7, 2024. It is now read-only.

Week3 submission #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions week3/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions week3/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.5"
66 changes: 66 additions & 0 deletions week3/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,67 @@
use std::any::TypeId;

enum Shape {
Circle { radius: f64 },
Square { length: f64 },
Rectangle { width: f64, height: f64 },
}

fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle { radius } => radius * radius * std::f64::consts::PI,
Shape::Square { length } => length * length,
Shape::Rectangle { width, height } => width * height,
}
}

#[test]
fn test_shape_areas() {
assert_eq!(area(&Shape::Circle { radius: 1.0 }), std::f64::consts::PI);
assert_eq!(area(&Shape::Square { length: 2.0 }), 4.0);
assert_eq!(
area(&Shape::Rectangle {
width: 3.0,
height: 8.0
}),
24.0
);
}

fn random_shape() -> Shape {
match rand::random::<i32>() % 3 {
0 => Shape::Circle {
radius: rand::random(),
},
1 => Shape::Square {
length: rand::random(),
},
_ => Shape::Rectangle {
width: rand::random(),
height: rand::random(),
},
}
}

fn circle_area(shape: &Shape) -> Option<f64> {
if let Shape::Circle { .. } = shape {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I somehow ended up having to use this syntax .. but I'm not sure what it actually does in this context. Can you explain?

Option::Some(area(shape))
} else {
Option::None
}
}

#[test]
fn test_circle_area() {
assert_eq!(
circle_area(&Shape::Circle { radius: (1.0) }),
Some(std::f64::consts::PI)
);
assert_eq!(
circle_area(&Shape::Rectangle {
width: 1.0,
height: 1.0
}),
None
);
assert_eq!(circle_area(&Shape::Square { length: 1.0 }), None);
}