我问了一个相关问题关于为什么没有实施From<&String>
for 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
所以它没有找到一个实现Into<String>
for &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`
对我来说,这是编译器声称存在真正的冲突,而不是潜在的冲突。