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 都能提供所需的功能和支持。

相关推荐
Vex2une25 分钟前
Google Picasa 精神续作:Rust 重写的离线本地相册工具‌
rust·图片管理·picasa·马良·本地照片管理·重复图片检测·maliang
Zhao-Jichao2 小时前
AI Prompting for Everyone 课程笔记 - P21 总结 Conclusion
人工智能·笔记
欢欢李3 小时前
【LTE L3 笔记 05】LTE同步信号
笔记·无线通信·物理层·lte·空口协议
La Pulga4 小时前
【FreeRTOS源码学习笔记】空闲任务与阻塞延时
笔记·mcu·学习·嵌入式·freertos·实时操作系统
蒸蒸yyyyzwd4 小时前
秋招学习笔记 day106
笔记·学习
小李不想当小白6 小时前
WDG看门狗(STM32标准库学习笔记)
笔记·stm32·单片机·嵌入式硬件·学习·嵌入式
欢欢李6 小时前
【LTE L3 笔记 04】LTE帧结构
笔记·无线通信·物理层·lte·空口协议
Zhao-Jichao8 小时前
AI Prompting for Everyone 课程笔记 - P20 实验与期末项目 Lab and Final Project
前端·人工智能·笔记
lisw059 小时前
作为人类代理的大语言模型及其角色分类!
人工智能·学习·语言模型
Z21-X9 小时前
云原生运维实战笔记:企业网站综合上云部署与云运维服务全景解析
运维·笔记·学习·云原生