Rust Polymorphism Simple Example

警告
本文最后更新于 2024-02-24,文中内容可能已过时。

使用 Enum 和 Trait 解决经典多态问题

长方形,三角形,圆形的面积周长计算

rust

enum Shape { 
    Rectangle { width:f32, height:f32 },
    Triangle { side:f32},
    Circ { radius:f32 },
}
impl Shape {
    pub fn perimeter(&self) -> f32 {
        match self {
            Shape::Rectangle { width, height } => width*2.0+height*2.0,
            Shape::Triangle { side } => side*3.0,
            Shape::Circ { radius } => 2.0*std::f32::consts::PI*radius,
        }
    }
    pub fn area(&self) -> f32 {
        match self {
            Shape::Rectangle { width, height } => width*height,
            Shape::Triangle { side } => side*0.5*3.0_f32.sqrt(),
            Shape::Circ { radius } => std::f32::consts::PI*radius*radius,
        }
    }
}
fn main() {
    let rectangle = Shape::Rectangle { width:1.0, height:2.0 };
    let triangle = Shape::Triangle { side:1.0 };
    let cric = Shape::Circ { radius:1.0 };

    dbg!(rectangle.perimeter(),rectangle.area());
    dbg!(triangle.perimeter(),triangle.area());
    dbg!(cric.perimeter(),cric.area());
}

结果

text

   Compiling polymorphism v0.1.0 (D:\rustcode\polymorphism)
    Finished dev [unoptimized + debuginfo] target(s) in 0.61s
     Running `target\debug\polymorphism.exe`
[src\main.rs:27] rectangle.perimeter() = 6.0
[src\main.rs:27] rectangle.area() = 2.0
[src\main.rs:28] triangle.perimeter() = 3.0
[src\main.rs:28] triangle.area() = 0.8660254
[src\main.rs:29] cric.perimeter() = 6.2831855
[src\main.rs:29] cric.area() = 3.1415927

rust

trait Shape {
    fn perimeter(&self) -> f32;
    fn area(&self) -> f32;
}
struct Rectangle { width:f32, height:f32 }
struct Triangle { side:f32}
struct Circle { radius:f32 }
impl Shape for Rectangle {
    fn perimeter(&self) -> f32 { self.width*2.0+self.height*2.0 }
    fn area(&self) -> f32 { self.width*self.height }
}
impl Shape for Triangle {
    fn perimeter(&self) -> f32 { self.side*3.0 }
    fn area(&self) -> f32 { self.side*0.5*3.0_f32.sqrt() }
}
impl Shape for Circle {
    fn perimeter(&self) -> f32 { 2.0*std::f32::consts::PI*self.radius }
    fn area(&self) -> f32 { std::f32::consts::PI*self.radius*self.radius }
}
fn main() {
    let rectangle = Rectangle { width:1.0, height:2.0 };
    let triangle = Triangle { side:1.0 };
    let cric = Circle { radius:1.0 };

    dbg!(rectangle.perimeter(),rectangle.area());
    dbg!(triangle.perimeter(),triangle.area());
    dbg!(cric.perimeter(),cric.area());
}

结果

text

   Compiling polymorphism v0.1.0 (D:\rustcode\polymorphism)
    Finished dev [unoptimized + debuginfo] target(s) in 0.58s
     Running `target\debug\polymorphism.exe`
[src\main.rs:25] rectangle.perimeter() = 6.0
[src\main.rs:25] rectangle.area() = 2.0
[src\main.rs:26] triangle.perimeter() = 3.0
[src\main.rs:26] triangle.area() = 0.8660254
[src\main.rs:27] cric.perimeter() = 6.2831855
[src\main.rs:27] cric.area() = 3.1415927