[英]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.