Rust dyn - 动态分发 trait 对象

dyn - 动态分发 trait 对象

dyn是关键字,用于指示一个类型是动态分发(dynamic dispatch),也就是说,它是通过trait object实现的。这意味着这个类型在编译期间不确定,只有在运行时才能确定。

  • practice

trait object实现多态性。

假设有一个几何图形的类层次结构,例如圆形(Circle)和矩形(Rectangle),每种几何图形都有一个计算面积的方法。定义trait Shape来表示这个特征,并在每个几何图形中实现这个trait。

rust 复制代码
trait Shape {
    fn area(&self) -> f64;
}

struct Circle {
    radius: f64,
}

impl Shape for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }
}

struct Rectangle {
    width: f64,
    height: f64,
}

impl Shape for Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }
}

现在编写一个函数,可以计算不同类型几何图形的总面积。我们可以使用trait object来实现这个函数:

rust 复制代码
fn total_area(shapes: &[&dyn Shape]) -> f64 {
    let mut total = 0.0;
    for shape in shapes {
        total += shape.area();
    }
    total
}

&[&dyn Shape]类型的参数来接受几何图形的数组。数组中的每个元素都是一个对实现Shape trait的具体类型的引用。使用for循环遍历这个数组,并对每个元素调用area方法,计算它的面积,并将结果累加到总面积中。

创建一些具体的几何图形实例,并将它们传递给total_area函数,以计算它们的总面积:

rust 复制代码
fn main() {
    let shapes: Vec<&dyn Shape> = vec![
        &Circle { radius: 1.0 },
        &Rectangle { width: 3.0, height: 4.0 },
        //&Circle { radius: 1.5 },
    ];
    let total = total_area(&shapes);
    println!("Total area: {}", total);
}

输出结果正确:

相关推荐
神话20098 小时前
Rust 初体验与快速上手指南
android·rust
tang7778910 小时前
爬虫如何绕过绕过“5秒盾”Cloudflare:从浏览器指纹模拟到Rust求解之不完全指南
开发语言·爬虫·rust·cloudflare
Yuer202510 小时前
什么是 Rust 语境下的“量化算子”——一个工程对象的最小定义
开发语言·后端·rust·edca os·可控ai
古城小栈13 小时前
Rust 交叉编译:Windows ====> Linux (musl 静态编译)
linux·windows·rust
张心独酌14 小时前
Rust新手练习案例库- rust-learning-example
开发语言·后端·rust
木木木一16 小时前
Rust学习记录--C11 编写自动化测试
java·学习·rust
FAFU_kyp17 小时前
Rust 字符串与切片
开发语言·后端·rust
superman超哥19 小时前
实时互动的基石:Rust WebSocket 实现的架构之美
开发语言·rust·编程语言·rust websocket·rust实施互通·rust架构之美
木木木一20 小时前
Rust学习记录--C0 总目录
开发语言·学习·rust
Mr -老鬼20 小时前
Java、Go、Rust高并发时代“称雄”之战:场景适配与生态博弈
java·golang·rust