Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Operators not overloaded properly for primitives #20251

Closed
ibab opened this issue Dec 26, 2014 · 2 comments
Closed

Operators not overloaded properly for primitives #20251

ibab opened this issue Dec 26, 2014 · 2 comments

Comments

@ibab
Copy link

ibab commented Dec 26, 2014

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.

@japaric
Copy link
Member

japaric commented Dec 26, 2014

Duplicate of #19035 (also see #8280)

Is this intended behaviour?

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
Copy link
Author

ibab commented Dec 27, 2014

Thanks for the quick info and sorry for the duplicate.

@ibab ibab closed this as completed Dec 27, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants