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

输出结果正确:

相关推荐
无名之逆3 小时前
你可能不需要WebSocket-服务器发送事件的简单力量
java·开发语言·前端·后端·计算机·rust·编程
Source.Liu5 小时前
【egui】界面的坐标系统:f32 一统江湖
rust·egui
班公湖里洗过脚10 小时前
Rust解析mp3文件及工作目录下多个项目维护示例
rust
sunny_21 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化
用户0235087373121 天前
第02篇:5分钟上手 blockcell —— 从安装到第一次对话
rust
badmonster01 天前
我写了一个超轻量MCP,让编码Agent真正理解你的代码——Token消耗减少70%,1分钟接入
rust·ai编程
RoyLin1 天前
10美元硬件中可运行的隐私 LLM 推理引擎
人工智能·rust·agent
Source.Liu1 天前
【egui】[特殊字符] 窗口配置小抄:eframe::NativeOptions
rust·egui
Hello.Reader1 天前
Tauri 项目结构前端壳 + Rust 内核,怎么协作、怎么构建、怎么扩展
开发语言·前端·rust
Source.Liu1 天前
【egui】[特殊字符]简单、快速、跨平台的 Rust GUI 库
rust·egui