【发布时间】:2021-06-18 10:56:36
【问题描述】:
我有一个类似于Iterator 的特征,以及围绕它的包装器:
pub struct Wrapped<I: Iterator>(I);
包装迭代器上的许多函数使用 impl-trait 返回新的包装迭代器。
impl <I: Iterator> Wrapped<I> {
pub fn foo(self) -> Wrapped<impl Iterator<Item=Foo<I::Item>>> {...}
pub fn bar(self) -> Wrapped<impl Iterator<Item=Bar<I::Item>>> {...}
}
这样一段时间后,用户就很容易忘记调用代码中迭代器项是什么(例如,对于像my_wrapped.foo().bar().bar().foo() 这样的表达式)。
我想给用户一种方法来明确指定他们期望Item 是什么类型,如果不是那种类型,那么就会出现编译时错误:
let y = x.foo().bar().bar().foo().assert_item_type::<Foo<Bar<Bar<Foo<X>>>>>()
但到目前为止,我发现这样做的唯一方法有点奇怪和丑陋。有没有更清洁的方法?
pub trait Is {
type Myself;
}
impl<T> Is for T {
type Myself = T;
}
impl <I: Iterator> Wrapped<I> {
pub fn assert_item_type<Item: Is<Myself = I::Item>>(self) -> Self {
self
}
}
【问题讨论】:
-
我想说的是,除了在
Wrapped上使用通用扩展特征而不是固有 impl 之外,您的方法尽可能干净。你不能在关联类型之外使用=(我相信现在),所以Istrait 是必要的。
标签: rust type-hinting associated-types