是否可以指定两个类型参数是不同的类型?

时间:2015-05-24 20:20:32

标签: generics rust

我有一个带有map方法的简单包装器结构。我还有一个错误枚举的层次结构,我已经实现From以便能够将Error1转换为Error2,允许try!宏自动为我转换:

struct Span<T>(T);

impl<T> Span<T> {
    fn map<F, U>(self, f: F) -> Span<U>
        where F: FnOnce(F) -> U
    {
        Span(f(self.0))
    }
}

enum Error1 { One }
enum Error2 { Two }

impl From<Error1> for Error2 {
    fn from(v: Error1) -> Error2 { Error2::Two }
}

我希望能够添加From实现,以便我也可以自动转换Span结构的内部:

impl<T,U> From<Span<T>> for Span<U>
    where U: From<T>
{
    fn from(v: Span<T>) -> Span<U> {
        v.map(|v| v.into())
    }
}

不幸的是,this fails

error[E0119]: conflicting implementations of trait `std::convert::From<Span<_>>` for type `Span<_>`:
  --> src/main.rs:18:1
   |
18 |   impl<T,U> From<Span<T>> for Span<U>
   |  _^ starting here...
19 | |     where U: From<T>
20 | | {
21 | |     fn from(v: Span<T>) -> Span<U> {
22 | |         v.map(|v| v.into())
23 | |     }
24 | | }
   | |_^ ...ending here
   |
   = note: conflicting implementation in crate `core`

错误消息未指向specific implementation of From,但我的猜测就是这个:

impl<T> From<T> for T

如果我的TU碰巧是相同的具体类型,那么我的实施可能会发生冲突。有什么方法可以为所有TU T!= U实现我的特质?

1 个答案:

答案 0 :(得分:4)

Unfortunately this is not yet possible and the best approach to this problem has not really been decided yet. One proposal that is slightly relevant to this situation is the idea of negative bounds (specifically equality bounds), but I think it has been deemed too complex. See the latest issue on the subject for more information, where the team members are considering different ideas, including specialization.