Skip to content

Instantly share code, notes, and snippets.

@sshaplygin
Created July 4, 2023 14:31
Show Gist options
  • Save sshaplygin/5728d84d574ec8b4c31392ca2f69a1f1 to your computer and use it in GitHub Desktop.
Save sshaplygin/5728d84d574ec8b4c31392ca2f69a1f1 to your computer and use it in GitHub Desktop.
Example usage vector with objects witch implemented common trait
trait Figure {
fn area(&self) -> f64;
}
struct Circle {
radius: f64,
}
struct Rectangle {
a: f64,
b: f64,
}
struct Square {
a: f64,
}
impl Figure for Circle {
fn area(&self) -> f64 {
self.radius * self.radius * 3.14
}
}
impl Figure for Square {
fn area(&self) -> f64 {
self.a * self.a
}
}
impl Figure for Rectangle {
fn area(&self) -> f64 {
todo!()
}
}
fn main() {
let figures: Vec<Box<dyn Figure>> = vec![
Box::new(Circle{radius:1.0}),
Box::new(Square{a:2.0}),
Box::new(Rectangle{a:1.0, b:2.0}),
];
for figure in figures.iter() {
println!("{}", figure.area())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment