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.

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

    Issue actions