【问题标题】:Is it possible to specify that two type parameters are different types?是否可以指定两个类型参数是不同的类型?
【发布时间】:2015-05-24 20:20:31
【问题描述】:

我有一个带有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

【问题讨论】:

    标签: generics rust


    【解决方案1】:

    不幸的是,这还不可能,解决这个问题的最佳方法还没有真正确定。与这种情况稍微相关的一个建议是negative bounds(特别是equality bounds)的想法,但我认为它被认为太复杂了。有关更多信息,请参阅有关该主题的 latest issue,团队成员正在考虑不同的想法,包括专业化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-19
      • 2011-12-18
      • 2020-03-23
      • 2021-10-26
      • 1970-01-01
      相关资源
      最近更新 更多