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);
}

输出结果正确:

相关推荐
该用户已不存在2 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
大卫小东(Sheldon)2 天前
写了一个BBP算法的实现库,欢迎讨论
数学·rust
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
ftpeak3 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
咸甜适中3 天前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
咸甜适中3 天前
rust语言 (1.88) egui (0.32.2) 学习笔记(逐行注释)(二十八)使用图片控件显示图片
笔记·学习·rust·egui
huli33203 天前
pingora_web:首款基于 Cloudflare Pingora 的企业级 Rust Web 框架
rust
Pomelo_刘金3 天前
如何优雅地抽离 Rust 子工程:以 rumqttd 为例
rust
几颗流星3 天前
Rust 常用语法速记 - 错误处理
后端·rust
向上的车轮3 天前
如何用 Rust 重写 SQLite 数据库(二):是否有市场空间?
数据库·rust·sqlite