知识卡片
本地包装实现外部特征
当特征与目标类型都来自其他 crate 时,不能直接为 Vec 添加本地的 Display 实现。定义 Wrapper(Vec) 后,Wrapper 是本地独立类型,可以为其实现 Display,并在实现中通过 self.0 使用内部向量。包装类型只向外开放需要的方法;另行实现 Deref 会增大可访问的内部操作范围。
相关卡片 [[新类型隔离单位与接口]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 高级特性 Disambiguating Between Methods with the Same Name · 查看原书依据
In “Implementing a Trait on a Type” on page 193, we mentioned the orphan rule that states we’re only allowed to implement a trait on a type if either the trait or the type, or both, are local to our crate. It’s possible to get around this restriction using the newtype pattern, which involves creating a new type in a tuple struct.
参考来源
- 位置:《The Rust Programming Language(第2版)》第19章 高级特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c19.xhtml`,块 0215)
- 结论依据:原文陈述孤儿规则及用本地单字段元组结构体承接外部 trait 实现的办法。
- 原始内容:In “Implementing a Trait on a Type” on page 193, we mentioned the orphan rule that states we’re only allowed to implement a trait on a type if either the trait or the type, or both, are local to our crate. It’s possible to get around this restriction using the newtype pattern, which involves creating a new type in a tuple struct.