Closed
Description
I'm trying to define a type that can be added/multiplied with floats.
I've tried overloading +
like this:
pub struct Num(f64);
impl Add<Num,Num> for f64 {
fn add(self, other: Num) -> Num {
match other {
Num(x) => Num(self + x)
}
}
}
But
let x = Num(42.0);
println!("{}", 1.0 + x);
fails with the following error:
error: mismatched types: expected `_`, found `Num` (expected floating-point variable, found struct Num)
println!("{}", 1.0 + x);
^
Interestingly,
let x: Num = Num(42.0);
println!("{}", 1.0.add(x));
works just fine.
Is this intended behaviour?
It seems inconsistent that +
simply ignores the implementation of Add
in this case.
Activity
japaric commentedon Dec 26, 2014
Duplicate of #19035 (also see #8280)
It's a known bug. The compiler relies on the type of the LHS when type checking a binary operator, and when it sees a primitive type (like
f32
) on the LHS it tries to use the built-in operation, rather than the overloaded one, which expects the RHS to have the same type as the LHS.The workaround is to always put your type on the LHS for commutative ops and just use the unsugared method call for the other binary ops.
I got a fix on #19434, but the reviewer is currently busy revamping the associated types feature, so it may take a little longer to land.
ibab commentedon Dec 27, 2014
Thanks for the quick info and sorry for the duplicate.