簡體   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