知识卡片

普通读书笔记卡 · 6074.d.1.a.11 · 生成模型:未记录

特征定义共享操作

理解等级:中级

trait 声明共同操作的签名,各类型可按自己的数据实现。Summary 的 summarize 都接收 &self 并返回 String,但新闻稿可能拼接作者与标题,短讯可能拼接账号与正文。在跨 crate 通过方法语法使用时,可把相应 trait 引入作用域。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0124) - 结论依据:原文对比 trait 实现与常规方法实现,规定 impl Trait for Type 和签名对应关系。 - 原始内容:Implementing a trait on a type is similar to implementing regular methods. The difference is that after impl, we put the trait name we want to implement, then use the for keyword, and then specify the name of the type we want to implement the trait for. Within the impl block, we put the method signatures that the trait definition has defined.