当前位置: 首页 > news >正文

Rust进阶-part5-trait

Rust进阶[part5]_trait

trait概述

在 Rust 中,trait 是一种定义共享行为的方式。它类似于其他语言中的接口,允许我们定义一组方法签名,然后让不同的类型去实现这些方法。通过 trait,我们可以实现多态性,即不同类型可以以统一的方式处理。

普通实现

  • 使用 trait 关键字来声明一个特征
  • summary 是特征名
  • 在大括号中定义了该特征的所有方法
// 定义一个 trait
trait Summary {fn summarize(&self) -> String;
}// 定义一个结构体
struct NewsArticle {headline: String,location: String,author: String,content: String,
}// 为 NewsArticle 结构体实现 Summary trait
impl Summary for NewsArticle {fn summarize(&self) -> String {format!("{}, by {} ({})", self.headline, self.author, self.location)}
}// 定义另一个结构体
struct Tweet {username: String,content: String,reply: bool,retweet: bool,
}// 为 Tweet 结构体实现 Summary trait
impl Summary for Tweet {fn summarize(&self) -> String {format!("{}: {}", self.username, self.content)}
}fn main() {let article = NewsArticle {headline: String::from("Penguins win the Stanley Cup Championship!"),location: String::from("Pittsburgh, PA, USA"),author: String::from("Iceburgh"),content: String::from("The Pittsburgh Penguins once again are the best \hockey team in the NHL."),};let tweet = Tweet {username: String::from("horse_ebooks"),content: String::from("of course, as you probably already know, people"),reply: 
http://www.xdnf.cn/news/1253107.html

相关文章:

  • 机器学习——朴素贝叶斯
  • 19day-人工智能-机器学习-分类算法-决策树
  • NCD57080CDR2G 安森美onsemi 通用驱动器, SOIC, 8针, 20V电源, 8 A输出NCD57080CDR2电流隔离式栅极驱动器
  • 大模型后训练——Online-RL基础
  • 【嵌入式电机控制#26】BLDC:三相模拟采集
  • 江协科技STM32 15-1 FLASH闪存
  • LinkedList 深度解析:核心原理与实践
  • Docker 常用命令介绍
  • Linux 中 Git 操作大全
  • Web 端 AI 图像生成技术的应用与创新:虚拟背景与创意图像合成
  • 初识神经网络01——认识PyTorch
  • docker-compose快速部署启动file beat+ELK
  • WMS及UI渲染底层原理学习
  • 完整的登陆学生管理系统(配置数据库)
  • 数字图像处理(冈萨雷斯)第三版:第四章——空间滤波与频域滤波(平滑与锐化)——主要内容和重点
  • 无人机航拍数据集|第6期 无人机垃圾目标检测YOLO数据集772张yolov11/yolov8/yolov5可训练
  • 当前主流GPU全景讲解:架构、功能与应用方向
  • 【模电笔记】—— 直流稳压电源——稳压电路
  • OpenCV校准双目相机并测量距离
  • linux下的串口通信原理及编程实例
  • Pytest项目_day04(Python做接口请求)
  • 笔记html模板
  • 大语言模型
  • Python Pandas.lreshape函数解析与实战教程
  • CPP网络编程-异步sever
  • 《爬虫实战指南:轻松获取店铺详情,开启数据挖掘之旅》
  • 机器学习-LinearRegression
  • 【20205CVPR-目标检测方向】基于事件的高效目标检测:具有空间和时间注意力的混合神经网络
  • QT----QAxObject在子线程中调用,发现excel指针为空
  • Kubesphere搜索镜像问题