我問了relevant question爲什麼沒有執行From<&String>
String
。我現在想創建自己的特點如下所示:如果`Into <String>`沒有爲`&String`實現,爲什麼這些實現衝突?
#[derive(Debug)]
struct MyStruct(String);
impl MyStruct {
fn new<T>(t: T) -> MyStruct
where
T: MyIntoString,
{
MyStruct(t.my_into())
}
}
trait MyIntoString {
fn my_into(self) -> String;
}
impl<'a> MyIntoString for &'a String {
fn my_into(self) -> String {
self.clone()
}
}
impl<I> MyIntoString for I
where
I: Into<String>,
{
fn my_into(self) -> String {
self.into()
}
}
fn main() {
let s: String = "Hello world!".into();
let st: MyStruct = MyStruct::new(&s);
println!("{:?}", st);
}
編譯器現在聲稱的MyIntoString
兩個實現是相互矛盾的。這對我來說更是如此,因爲我們已經在另一個問題中看到From<&String>
沒有爲String
實施,所以它沒有找到的執行&String
。那麼現在如何來衝突呢?
此外,即使當我打開#![feature(specialization)]
時,也檢測到相同的衝突。
錯誤消息
根據這個問題的一個答案,它看起來像錯誤消息並沒有指導我在正確的軌道。
因此,讓我發佈錯誤消息的責任,因爲它可能在未來發生變化。
error[E0119]: conflicting implementations of trait `MyIntoString` for type `&std::string::String`:
--> src/main.rs:23:1
|
17 |/impl<'a> MyIntoString for &'a String {
18 | | fn my_into(self) -> String {
19 | | self.clone()
20 | | }
21 | | }
| |_- first implementation here
22 |
23 |/impl<I> MyIntoString for I
24 | | where
25 | | I: Into<String>,
26 | | {
... |
29 | | }
30 | | }
| |_^ conflicting implementation for `&std::string::String`
對我來說,這是編譯器聲稱存在真正的衝突,而不是潛在的衝突。
相關:https://stackoverflow.com/questions/45033704/why-do-i-get-conflicting-implementations-of-trait-for-f32-which-does-not簡單 – Boiethios