【发布时间】:2017-07-17 20:29:04
【问题描述】:
我向relevant question 询问了为什么String 没有实现From<&String>。我现在想创建自己的 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`
对我来说,这是编译器声称存在真正的冲突,而不是潜在的冲突。
【问题讨论】: