[英]using const generic in implementation of trait for another trait causes "unconstrained const parameter" error
[英]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倍:
where
子句是否允许重叠是非常复杂的, where
子句比另一个更专业是非常复杂的(即将到来的专业化), 前两个是纯粹的实现细节,但后者在语言设计方面是一个真正的问题。 设想:
Copy
绑定, impl Into<i64> for &str
添加impl Into<i64> for &str
。 突然间,发生了一场之前没有冲突的冲突! 你无法升级!
所以这里有一个真正的设计选择。 你需要选择:
你不能两者兼得。
注意:尝试在您选择的搜索引擎中键入Rust explain <code>
, 看看E0119 。 虽然这里没什么用处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.