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

输出结果正确:

相关推荐
Ramble_Naylor1 小时前
Rust深度解读:Send 与 Sync 的本质与线程安全边界
python·算法·rust
Ramble_Naylor5 小时前
Rust深度解读:异步流(Async Streams)与生成器的处理艺术
开发语言·后端·rust
RobinDevNotes8 小时前
Memvid 把 Agent 长期记忆塞进一个文件
人工智能·rust·openresty
miofly10 小时前
GitHub 今日推荐|agent-desktop:通过无障碍树让 AI 代理直接操作桌面应用
rust·开源·github
geovindu10 小时前
rust:N-Barrier Pattern
开发语言·后端·设计模式·rust·屏障模式·并发型模式
Ramble_Naylor11 小时前
Rust深度解读:高性能 Web 网关与 Axum 架构剖析
前端·架构·rust
Hello.Reader12 小时前
100 人同时操作一座三维城市,为什么不需要服务器渲染 6000 帧?Rust + wgpu 多端并发架构实战
服务器·架构·rust
遇码1 天前
2026-11-01-daw-retry-banner-body
人工智能·ai·rust·数据分析·大模型·agent
不积跬步无以至千里mmbb261 天前
rust_analysis
开发语言·后端·rust
怪我冷i2 天前
Rust 的impl语法详解
开发语言·后端·rust