rust学习笔记20-Trait

Rust 的 trait 是定义类型行为的核心机制,类似于其他语言中的接口(interface),但功能更强大。它是 Rust 实现多态(polymorphism)和抽象的核心工具。

定义 trait

使用 trait 关键字定义一组方法签名(可包含默认实现):

rust 复制代码
trait HasArea {
    fn area(&self) -> f64;
    fn print_area(&self) {
        println!("面积是:{}", &self.area());
    }
}

HasArea规定了实现者必需有 area(&self) -> f64方法。还实现了带默认方法的print_area。这是特性与接口的不同点:接口只能规范方法而不能定义方法,但特性可以定义方法作为默认方法,因为是"默认",所以对象既可以重新定义方法,也可以不重新定义方法使用默认的方法:

为类型实现 trait

impl <特性名> for <所实现的类型名>

Rust 同一个类可以实现多个特性,每个 impl 块只能实现一个。

rust 复制代码
struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

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

struct Square {
    x: f64,
    y: f64,
    side: f64,
}

impl HasArea for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

2. 核心用法

作为接口使用

通过 trait 约束泛型类型的行为:

rust 复制代码
fn print_area<T: HasArea>(shape: &T) {
    println!("shape 的面积是 {}", shape.area());
}

fn main() {
    let c = Circle { x: 0.0, y: 0.0, radius: 1.0 };
    let s = Square { x: 0.0, y: 0.0, side: 2.0 };

    print_area(&c);
    print_area(&s);
}
动态分发(Trait 对象)

使用 dyn Trait 实现运行时多态,即在运行时决定调用哪个方法,这可以通过 Trait 对象来实现。Trait 对象允许你存储不同类型的值,只要这些类型实现了相同的 Trait。

rust 复制代码
fn print_area_dyn(shape: &dyn HasArea) {
    println!("shape 的面积是  {}", shape.area());
}

fn main() {
    let c = Circle { x: 0.0, y: 0.0, radius: 1.0 };
    let s = Square { x: 0.0, y: 0.0, side: 2.0 };

    print_area_dyn(&c);
    print_area_dyn(&s);
}

3. 高级特性

关联类型(Associated Types)

在 trait 中定义类型占位符,由实现者指定具体类型:

rust 复制代码
trait Iterator {
    type Item; // 关联类型
    fn next(&mut self) -> Option<Self::Item>;
}

struct Counter(u32);

impl Iterator for Counter {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> {
        self.0 += 1;
        Some(self.0)
    }
}
泛型 trait

定义带泛型参数的 trait:

rust 复制代码
trait Converter<T> {
    fn convert(&self) -> T;
}

impl Converter<String> for i32 {
    fn convert(&self) -> String {
        self.to_string()
    }
}
Trait 继承

一个 trait 可以继承多个父 trait:

rust 复制代码
trait Animal {
    fn name(&self) -> &str;
}

trait Mammal: Animal { // 继承 Animal
    fn walk(&self) {
        println!("{} is walking", self.name());
    }
}

struct Dog;
impl Animal for Dog {
    fn name(&self) -> &str { "Dog" }
}
impl Mammal for Dog {}

fn main() {
    let d = Dog{};
    d.name();
    d.walk();
}

4. 对象安全(Object Safety)

只有满足以下条件的 trait 才能作为 trait 对象(dyn Trait)使用:

  1. 方法不返回 Self

  2. 方法没有泛型参数。

  3. Trait 不要求 Self: Sized 约束。

示例(非对象安全的 trait)

rust 复制代码
trait Cloneable {
    fn clone(&self) -> Self; // 返回 Self,违反对象安全
}

// 错误!无法转换为 `dyn Cloneable`
let obj: Box<dyn Cloneable> = Box::new(42);

5. 常见标准库 Trait

Clone / Copy:复制语义。

Debug / Display:格式化输出。

PartialEq / Eq:相等比较。

PartialOrd / Ord:排序比较。

From / Into:类型转换。

Default:默认值。

Drop:自定义析构逻辑。

6. 典型使用场景

多态行为抽象(如 GUI 组件的 draw 方法)。

泛型约束(限制泛型类型的能力)。

运算符重载(通过实现 Add、Mul 等 trait)。

错误处理(标准 Error trait)。

迭代器模式(Iterator trait)。

总结

Trait 在 Rust 中是非常强大的工具,用于定义共享行为、实现多态性以及提供灵活的接口设计。通过 Trait,你可以编写高度模块化和可复用的代码,同时保持静态类型系统的安全性和性能优势。无论是简单的接口定义还是复杂的泛型编程,Trait 都能提供所需的功能和支持。

相关推荐
-Springer-6 分钟前
STM32 学习 —— 个人学习笔记9-3(FlyMcu 串口下载)
笔记·stm32·学习
weixin_4588726141 分钟前
东华复试OJ每日3题打卡·复盘103~105
学习
SuniaWang1 小时前
《Spring AI + 大模型全栈实战》学习手册系列 ·专题三:《Embedding 模型选型指南:从 MMTEB 排名到实际应用》
人工智能·学习·spring
问道飞鱼1 小时前
【Tauri框架学习】Windows 11 环境下 Tauri 开发环境安装与问题解决手册
windows·学习·tauri·开发环境
中屹指纹浏览器1 小时前
2026指纹浏览器与代理IP协同安全体系构建——从特征匹配到行为风控的全链路防护
经验分享·笔记
لا معنى له2 小时前
什么是Active Inference(主动推理)? ——学习笔记
笔记·学习
weixin_387534222 小时前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
JicasdC123asd2 小时前
并行双分支瓶颈架构改进YOLOv26异构卷积核协同特征提取与残差学习双重突破
学习·yolo·架构
zhouping@2 小时前
JAVA学习笔记day06
java·笔记·学习
Jack.Jia2 小时前
GPS原理笔记三——GPS卫星轨道理论和计算
笔记