知识卡片
泛型把变化的类型参数化
抽取函数可以把变化的值换成参数。若两份逻辑还只在输入和输出类型上不同,则把类型也提取为参数。largest(list: &[T]) -> &T 表达返回值引用某个 T。函数体还依赖比较运算,所以需要 T: PartialOrd。选取第一项作初值的算法同时要求输入非空。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 泛型类型、trait 与生命周期 Removing Duplication by Extracting a Function · 查看原书依据
The help text mentions std::cmp::PartialOrd, which is a trait, and we’re going to talk about traits in the next section. For now, know that this error states that the body of largest won’t work for all possible types that T could be. Because we want to compare values of type T in the body, we can only use types whose values can be ordered.
参考来源
- 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0051)
- 结论依据:原文通过比较运算不能应用于任意 T 的错误,给出限制泛型使用范围的实际依据。
- 原始内容:The help text mentions std::cmp::PartialOrd, which is a trait, and we’re going to talk about traits in the next section. For now, know that this error states that the body of largest won’t work for all possible types that T could be. Because we want to compare values of type T in the body, we can only use types whose values can be ordered.