【Rust】泛型 trait

环境

  • Rust 1.56.1
  • VSCode 1.61.2

概念

参考:https://doc.rust-lang.org/stable/rust-by-example/generics/gen_trait.html

示例

trait 现在还没有一个统一的翻译,之后就直接称呼为 trait,不进行翻译。

main.rs

struct Empty;
struct Null;

// 泛型 trait
trait DoubleDrop<T> {
    fn double_drop(self, _: T);
}

// 实现泛型 trait,实现过程还带有泛型
impl<T, U> DoubleDrop<T> for U {
    fn double_drop(self, _: T) {}
}

fn main() {
    let empty = Empty;
    let null = Null;

    // 已经进行了移动
    empty.double_drop(null);

    // 编译错误,值已经进行了移动
    // empty;
    // null;
}

总结

了解了 Rust 中定义和使用泛型 trait。

附录

posted @   jiangbo4444  阅读(237)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-12-07 spring-boot 几个工具类(七)
2019-12-07 spring-boot 连接数据库(六)
2019-12-07 spring-boot 使用 jackson 出错(五)
2019-12-07 spring-boot 使用servlet2.5(四)
点击右上角即可分享
微信分享提示