繁体   English   中英

E0119错误与通用特征实现

[英]E0119 error with generic trait implementation

我有一个枚举:

enum Field {
    Str(String),
    Integer(i64),
}

我想要做:

impl From<String> for Field {
    fn from(s: String) -> Field {
        Field::Str(s)
    }
}

impl<I> From<I> for Field where I: Into<i64> + Copy {
    fn from(i: I) -> Field {
        Field::Integer(Into::<i64>::into(i))
    }
}

上面的代码有错误:

error[E0119]: conflicting implementations of trait
`std::convert::From<std::string::String>` for type `Field`:
--> <anon>:12:5
   |
6  |          impl From<String> for Field {
   |  ________- starting here...
7  | |       fn from(s: String) -> Field {
8  | |         Field::Str(s)
9  | |       }
10 | |     }
   | |_____- ...ending here: first implementation here
11 | 
12 |       impl<I> From<I> for Field where I: Into<i64> + Copy {
   |  _____^ starting here...
13 | |       fn from(i: I) -> Field {
14 | |         Field::Integer(Into::<i64>::into(i))
15 | |       }
16 | |     }
   | |_____^ ...ending here: conflicting implementation for `Field`

String不是Into<i64>的实现者,为什么错误E0119会发生?

TL; DR: where子句不计算在内。


问题的关键在于冲突检测目前仅基于模式 :它不考虑where子句。

问题是3倍:

  1. 决定where子句是否允许重叠是非常复杂的,
  2. 决定哪个where子句比另一个更专业是非常复杂的(即将到来的专业化),
  3. 允许否定推理意味着在库代码中添加特征实现现在是一个重大改变。

前两个是纯粹的实现细节,但后者在语言设计方面是一个真正的问题。 设想:

  • 您的代码没有Copy绑定,
  • Rust团队决定使解析更容易,并impl Into<i64> for &str添加impl Into<i64> for &str

突然间,发生了一场之前没有冲突的冲突! 你无法升级!

所以这里有一个真正的设计选择。 你需要选择:

  • 能写出不冲突的impl(还),
  • 能够无痛地升级您的依赖项。

你不能两者兼得。


注意:尝试在您选择的搜索引擎中键入Rust explain <code>看看E0119 虽然这里没什么用处。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM