TAIT(Type alias impl Trait)的伪装与解构
稳定版中已经存在的impl Trait在类型别名中的局限,以及nightly TAIT如何改变抽象模式 · 难度:入门 · +10XP
TAIT(Type alias impl Trait)的伪装与解构
Rust中impl Trait在函数返回位置可隐藏具体类型,但无法命名为类型别名——除非使用#![feature(type_alias_impl_trait)]。本课程说明为什么TAIT对抽象模块边界至关重要,例如异构集合或递归类型。将对比GAT、Box
#![feature(type_alias_impl_trait)]
// 定义一个递归的impl Trait类型别名
type Counter = impl Iterator- ;
fn make_counter(start: u32) -> Counter {
std::iter::successors(Some(start), |&n| Some(n + 1))
}
// 返回不同具体类型但统一为Counter
fn make_another_counter(start: u32) -> Counter {
(start..).take(10)
}
// 无法编译!因为type_alias_impl_trait要求所有返回路径必须是同一具体类型