知识卡片
特征约束决定方法可用性
泛型类型可以把总是成立的操作与仅对特定 T 成立的操作分开放入 impl。例如 Pair 都能通过 new 构造,cmp_display 仅在 T 同时实现 PartialOrd 和 Display 时出现。编译期据此判断调用是否有效。
相关卡片 [[实例与方法各声明泛型]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 泛型类型、trait 与生命周期 Traits as Parameters · 查看原书依据
By using a trait bound with an impl block that uses generic type parameters, we can implement methods conditionally for types that implement the specified traits. For example, the type Pair<T> in Listing 10-15 always implements the new function to return a new instance of Pair<T> (recall from “Defining Methods” on page 97 that Self is a type alias for the type of the impl block, which in this case
参考来源
- 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0183)
- 结论依据:原文直接对照 Pair<T> 的无条件构造与带两种约束的方法。
- 原始内容:By using a trait bound with an impl block that uses generic type parameters, we can implement methods conditionally for types that implement the specified traits. For example, the type Pair<T> in Listing 10-15 always implements the new function to return a new instance of Pair<T> (recall from “Defining Methods” on page 97 that Self is a type alias for the type of the impl block, which in this case