Skip to content

Operators not overloaded properly for primitives #20251

Closed
@ibab

Description

@ibab

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

japaric commented on Dec 26, 2014

@japaric
Member

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

ibab commented on Dec 27, 2014

@ibab
Author

Thanks for the quick info and sorry for the duplicate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @ibab@japaric

        Issue actions

          Operators not overloaded properly for primitives · Issue #20251 · rust-lang/rust