这是一个玩具示例:
#[derive(Debug)]
struct Int {
    v: i32,
}
#[derive(Debug)]
struct Double {
    v: f64,
}
impl Into<Double> for Int {
    fn into(self) -> Double {
        Double {
            v: f64::from(self.v),
        }
    }
}
这个工作,但我真的要实现Into<Double>了&Int和&mut Int.这不起作用:
impl<T> Into<Double> for T
where
    T: AsRef<Int>,
{
    fn into(self) -> Double {
        Double {
            v: f64::from(self.as_ref().v),
        }
    }
}
因为trait Into我的箱子里没有定义:
error[E0119]: conflicting implementations of trait `std::convert::Into<Double>`:
  --> src/main.rs:19:1
   |
19 | / impl<T> Into<Double> for T
20 | | where
21 | |     T: AsRef<Int>,
22 | | {
...  |
27 | |     }
28 | | }
   | |_^
   |
   = note: conflicting implementation in crate `core`:
           - impl<T, U> std::convert::Into<U> for T
             where U: std::convert::From<T>;
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`); only traits defined in the current crate can be implemented for a type parameter
  --> src/main.rs:19:1
   |
19 | / impl<T> Into<Double> for T
20 | | where
21 | |     T: AsRef<Int>,
22 | | {
...  |
27 | |     }
28 | | }
   | |_^
我应该如何实现Into<Double>,&Int并且&mut Int没有代码重复,如:
impl<'a> Into<Double> for &'a Int {
impl<'a> Into<Double> for &'a mut Int {
impl<T> From<T> for Double
where
    T: AsRef<Int>,
{
    fn from(i: T) -> Self {
        Double {
            v: f64::from(i.as_ref().v),
        }
    }
}
这样我们就可以避免为for T孤立规则不允许的泛型参数(部分)实现特征.From并Into与这个令人敬畏的毯子impl链接在一起:
impl<T, U> Into<U> for T 
where
    U: From<T>, 
但是,AsRef这不是你在这里寻找的特质(我想).Borrow可能更适合你的情况:
impl<T> From<T> for Double
where
    T: Borrow<Int>,
{
    fn from(i: T) -> Self {
        Double {
            v: f64::from(i.borrow().v),
        }
    }
}
这样,转换就可以了Int,&Int并且&mut Int:
fn foo<T: Into<Double>>(_: T) {}
foo(Int { v: 3 });
foo(&Int { v: 3 });
foo(&mut Int { v: 3 });
也可以看看: