Skip to content

Simple operator overloading does not work #22743

Closed
@gibiansky

Description

@gibiansky

Apologies if this has been covered already or this is the wrong place to file this. This may be a bug or may simply be a lack of documentation, I'm not sure.

I have the following simple code:

use std::ops::Mul;

struct Foo {
    x: f64,
}

impl Mul<Foo> for f64 {
    type Output = Foo;

    fn mul(self, rhs: Foo) -> Foo {
        println!("Multiplying!");
        rhs
    }
}

pub fn main() {
    let f: Foo = Foo { x: 5.0 };
    let val: f64 = 3.0;
    let f2: Foo = val * f;
}

which results in the error message

test.rs:19:25: 19:26 error: mismatched types:
 expected `f64`,
    found `Foo`
(expected f64,
    found struct `Foo`) [E0308]
test.rs:19     let f2: Foo = val * f;
                                   ^
test.rs:19:19: 19:26 error: mismatched types:
 expected `Foo`,
    found `f64`
(expected struct `Foo`,
    found f64) [E0308]
test.rs:19     let f2: Foo = val * f;
                             ^~~~~~~
error: aborting due to 2 previous errors

This usage seems in line with the documentation and the tutorials. It may be related to #21188 and maybe #20749, but I am not sure.

How do I fix this or what am I doing wrong or why is this not working?

Version:

rustc 1.0.0-nightly (2b01a37ec 2015-02-21) (built 2015-02-21)
binary: rustc
commit-hash: 2b01a37ec38db9301239f0c0abcf3c695055b0ff
commit-date: 2015-02-21
build-date: 2015-02-21
host: x86_64-apple-darwin
release: 1.0.0-nightly

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions