Rust support type coercion for arguments for function calls, such as
fn foo(_: &usize) {}
fn main() {
let mut v = 10usize;
let v_mut_ref = &mut v;
foo(v_mut_ref);
}
But it is not working in function of trait with generic type
fn impl_add() {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Number(u64);
impl Add for Number {
type Output = Number;
fn add(self, other: Number) -> Number {
Number(self.0 + other.0)
}
}
impl Add<&Number> for Number {
type Output = Number;
fn add(self, other: &Number) -> Number {
Number(self.0 + other.0)
}
}
let one = Number(1);
let mut two = Number(2);
let two_ref = &two;
assert_eq!(one + two_ref, Number(3));
let two_mut_ref = &mut two;
assert_eq!(one.add(two_mut_ref as &Number), Number(3));
// assert_eq!(one.add(two_mut_ref), Number(3));
// assert_eq!(one + two_mut_ref, Number(3));
}
If I uncomment it, there will be an error like below
cannot add
&mut tests::impl_add::Number
totests::impl_add::Number
the traitAdd<&mut tests::impl_add::Number>
is not implemented fortests::impl_add::Number
the following other types implement traitAdd<Rhs>
: <tests::impl_add::Number as Add<&tests::impl_add::Number>> <tests::impl_add::Number as Add>rustcE0277
In my opinion, it is possible to first check if there is an implementation of Add<&mut Number>
, not to look for Add<&Number>
Why it doesn't work.