【发布时间】:2021-02-17 12:10:16
【问题描述】:
这段代码编译失败:
pub trait ToVec<T> {
fn to_vec(self) -> Vec<T>;
}
impl<I, T> ToVec<T> for I
where
I: Iterator<Item = T>,
{
fn to_vec(self) -> Vec<T> {
self.collect()
}
}
impl<'a, I, T> ToVec<T> for I
where
I: Iterator<Item = &'a T>,
T: Clone,
{
fn to_vec(self) -> Vec<T> {
self.cloned().collect()
}
}
错误:
error[E0119]: conflicting implementations of trait `ToVec<_>`:
--> src/lib.rs:14:1
|
5 | / impl<I, T> ToVec<T> for I
6 | | where
7 | | I: Iterator<Item = T>,
8 | | {
... |
11 | | }
12 | | }
| |_- first implementation here
13 |
14 | / impl<'a, I, T> ToVec<T> for I
15 | | where
16 | | I: Iterator<Item = &'a T>,
17 | | T: Clone,
... |
21 | | }
22 | | }
| |_^ conflicting implementation
据我了解,当给定类型I 实现Iterator 时,I::Item 只能有一个特定类型,因此它不能同时满足两种实现。
这是编译器的限制还是我的推理不正确?如果是这样,请提供一个同时满足这两个 impls 的示例。
【问题讨论】:
-
How to allow multiple implementations of a trait on various types of IntoIterator items? 中提到了同样的问题,但那里的解决方法似乎不适用于像您这样的情况。
标签: generics rust polymorphism traits parametric-polymorphism