-
Notifications
You must be signed in to change notification settings - Fork 1
/
area.rs
56 lines (47 loc) · 987 Bytes
/
area.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
pub trait Area {
fn area(&self) -> f64;
}
struct Circle {
radius: f64,
}
impl Area for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
struct Triangle {
base: f64,
height: f64,
}
impl Area for Triangle {
fn area(&self) -> f64 {
0.5 * self.base * self.height
}
}
struct Square {
side: f64,
}
impl Area for Square {
fn area(&self) -> f64 {
self.side * self.side
}
}
pub fn compute_area<T: Area>(shape: &T) -> f64 {
shape.area()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_area() {
let circle = Circle { radius: 5.0 };
let triangle = Triangle {
base: 10.0,
height: 8.0,
};
let square = Square { side: 6.0 };
assert_eq!(compute_area(&circle), 25f64 * std::f64::consts::PI);
assert_eq!(compute_area(&triangle), 40f64);
assert_eq!(compute_area(&square), 36f64);
}
}