Rust
Shapes with traits
Write a Shape trait and types that compute area.
Final task: shapes with a trait
Gather three different shapes behind a common trait and produce a report. Let the trait contain required methods and one default method:
trait Sekil {
fn ad(&self) -> &str;
fn alan(&self) -> f64;
fn cevre(&self) -> f64;
fn ozet(&self) -> String {
format!("{}: alan={:.2}, çevre={:.2}", self.ad(), self.alan(), self.cevre())
}
}
Heron's formula for a triangle's area: s = (a + b + c) / 2, area = √(s(s−a)(s−b)(s−c)).
The report
The shapes are kept in a Vec<Box<dyn Sekil>>; the default ozet produces the same format for each, and the total area is computed with an iterator:
let sekiller: Vec<Box<dyn Sekil>> = vec![
Box::new(Dikdortgen { en: 3.0, boy: 4.0 }),
Box::new(Daire { r: 1.0 }),
Box::new(Ucgen { a: 3.0, b: 4.0, c: 5.0 }),
];
for s in &sekiller {
println!("{}", s.ozet());
}
let toplam: f64 = sekiller.iter().map(|s| s.alan()).sum();
Exercise Shape report
Write the Sekil trait above and the types Dikdortgen, Daire and Ucgen (Heron); let their names be dikdörtgen, daire, üçgen. Print each shape's ozet() line, then toplam alan: X ({:.2}) at the end.
Show example solution
trait Sekil {
fn ad(&self) -> &str;
fn alan(&self) -> f64;
fn cevre(&self) -> f64;
fn ozet(&self) -> String {
format!("{}: alan={:.2}, çevre={:.2}", self.ad(), self.alan(), self.cevre())
}
}
struct Dikdortgen {
en: f64,
boy: f64,
}
struct Daire {
r: f64,
}
struct Ucgen {
a: f64,
b: f64,
c: f64,
}
impl Sekil for Dikdortgen {
fn ad(&self) -> &str {
"dikdörtgen"
}
fn alan(&self) -> f64 {
self.en * self.boy
}
fn cevre(&self) -> f64 {
2.0 * (self.en + self.boy)
}
}
impl Sekil for Daire {
fn ad(&self) -> &str {
"daire"
}
fn alan(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
fn cevre(&self) -> f64 {
2.0 * std::f64::consts::PI * self.r
}
}
impl Sekil for Ucgen {
fn ad(&self) -> &str {
"üçgen"
}
fn alan(&self) -> f64 {
let s = (self.a + self.b + self.c) / 2.0;
(s * (s - self.a) * (s - self.b) * (s - self.c)).sqrt()
}
fn cevre(&self) -> f64 {
self.a + self.b + self.c
}
}
fn main() {
let sekiller: Vec<Box<dyn Sekil>> = vec![
Box::new(Dikdortgen { en: 3.0, boy: 4.0 }),
Box::new(Daire { r: 1.0 }),
Box::new(Ucgen { a: 3.0, b: 4.0, c: 5.0 }),
];
for s in &sekiller {
println!("{}", s.ozet());
}
let toplam: f64 = sekiller.iter().map(|s| s.alan()).sum();
println!("toplam alan: {:.2}", toplam);
}
Test yourself
-
What is the area of a 3-4-5 triangle?
Show answer
6 — s = 6; √(6·3·2·1) = √36 = 6. Since it's a right triangle, 3·4/2 confirms it.
-
Square root
let s = (self.a + self.b + self.c) / 2.0;
(s * (s - self.a) * (s - self.b) * (s - self.c)).____()
Show answer
let s = (self.a + self.b + self.c) / 2.0;
(s * (s - self.a) * (s - self.b) * (s - self.c)).sqrt()
-
Shape and area
- Rectangle 3×4
- 12.00
- Daire r=1
- 3.14
- Triangle 3-4-5
- 6.00
- Toplam
- 21.14
Next lesson: Iterator adapter