我曾经问过一个有关为什么没有为 String
实现 From<&String>
的问题,链接如下:relevant question。现在我想创建自己的 trait,代码如下:
#[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
的Into<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`
对我来说,这是编译器声称存在一个真正的冲突,而不是潜在的冲突。