知识卡片
隐藏返回类型仍须统一
返回 impl Summary 表示实现方选定一种实现 Summary 的具体类型,调用方可使用承诺的 trait 行为。分支不能分别返回 NewsArticle 和 Tweet,即使两者都实现了 Summary。需要表达多种返回形态时可建立统一枚举或采用合适的 trait 对象。
相关卡片 [[输入约束表达类型关系]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 泛型类型、trait 与生命周期 Traits as Parameters · 查看原书依据
However, you can only use impl Trait if you’re returning a single type. For example, this code that returns either a NewsArticle or a Tweet with the return type specified as impl Summary wouldn’t work:
参考来源
- 位置:《The Rust Programming Language(第2版)》第10章 泛型类型、trait 与生命周期(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c10.xhtml`,块 0179)
- 结论依据:原文用试图返回不同具体类型的两个分支明确给出限制。
- 原始内容:However, you can only use impl Trait if you’re returning a single type. For example, this code that returns either a NewsArticle or a Tweet with the return type specified as impl Summary wouldn’t work: