我有一个元组向量:
let l = vec![(0, 1), (2, 3)];
我希望得到std::iter::Map
,它提取每个元组的第一个元素.天真的是,这招奏效了:
let m: std::iter::Map<_, _> = l.iter().map(|e| e.0);
现在,我想改为扩展Iterator
以使此伪代码工作:
let m: std::iter::Map<_, _> = l.iter().tuple_first();
try 1
我试着返回impl Iterator
:
trait TupleExtractor<'a, T1: 'a, T2: 'a>: Iterator<Item = &'a (T1, T2)> {
fn tuple_first(self) -> impl Iterator<Item = &'a T1>;
}
impl<'a, T1: 'a + Copy, T2: 'a, I> TupleExtractor<'a, T1, T2> for I
where
I: Iterator<Item = &'a (T1, T2)>,
{
fn tuple_first(self) -> impl Iterator<Item = &'a T1> {
self.map(|e| e.0)
}
}
此代码无法编译,因为
`impl Trait` only allowed in function and inherent method return types, not in trait method return types
try 2
我试图显式返回std::iter::Map
,而不是impl Iterator
.然而,出于同样的原因,这段代码也不能编译.
trait TupleExtractor<'a, T1: 'a, T2: 'a>: Iterator<Item = &'a (T1, T2)> {
fn tuple_first(
self,
) -> std::iter::Map<impl Iterator<Item = &'a (T1, T2)>, impl FnMut(&'a (T1, T2)) -> T1>;
}
impl<'a, T1: 'a + Copy, T2: 'a, I> TupleExtractor<'a, T1, T2> for I
where
I: Iterator<Item = &'a (T1, T2)>,
{
fn tuple_first(self) -> std::iter::Map<I, impl FnMut(&'a (T1, T2)) -> T1> {
self.map(|e| e.0)
}
}
try 3
由于try 2不起作用的原因是我不能指定std::iter::Map
的类型参数,所以我try 使它们成为类型参数:
trait TupleExtractor<'a, T1: 'a, T2: 'a, A, B>: Iterator<Item = &'a (T1, T2)> {
fn tuple_first(self) -> std::iter::Map<A, B>;
}
impl<'a, T1: 'a + Copy, T2: 'a, I, F> TupleExtractor<'a, T1, T2, I, F> for I
where
I: Iterator<Item = &'a (T1, T2)>,
F: FnMut(&'a (T1, T2)) -> T1,
{
fn tuple_first(self) -> std::iter::Map<I, F> {
self.map(|e: &'a (T1, T2)| e.0)
}
}
此代码无法编译,因为 the closure |e: &'a (T1, T2)| e.0
is not of the type F
:
= note: expected type parameter `F`
found closure `[closure@src/main.rs:38:18: 38:35]`
= help: every closure has a distinct type and so could not always match the caller-chosen type of parameter `F`
如何从特征法返回std::iter::Map
?我不想用Box
.