derive_more icon indicating copy to clipboard operation
derive_more copied to clipboard

Add `#[mul(forward_and_scalar)]`

Open Cannedfood opened this issue 8 months ago • 0 comments
trafficstars

Resolves #361

Synopsis

It currently isn't possible to use #[derive(Mul)] to implement multiplication with itself AND with a scalar at the same time.

Example:

fn without_forward() {
    #[derive(Clone, Copy, Mul)]
    pub struct Vec2 {
        pub x: f32,
        pub y: f32,
    }

    let a = Vec2 { x: 1.0, y: 2.0 };
    let c = a * Vec2 { x: 1.0, y: 1.0 }; // ❌ Doesn't work
    let d = a * 2.0;                     // ✔️ Works
}

fn with_forward() {
    #[derive(Clone, Copy, Mul)]
    #[mul(forward)]
    pub struct Vec2 {
        pub x: f32,
        pub y: f32,
    }

    let a = Vec2 { x: 1.0, y: 2.0 };
    let c = a * Vec2 { x: 1.0, y: 1.0 }; // ✔️ Works
    let d = a * 2.0;                     // ❌ Doesn't work
}

Solution

This commit adds a new attribute forward_and_scalar (feel free to suggest a better name) that enables both:

fn with_forward_and_scalar() {
    #[derive(Clone, Copy, Mul)]
    #[mul(forward_and_scalar)]
    pub struct Vec2 {
        pub x: f32,
        pub y: f32,
    }

    let a = Vec2 { x: 1.0, y: 2.0 };
    let c = a * Vec2 { x: 1.0, y: 1.0 }; // ✔️ Works
    let d = a * 2.0;                     // ✔️ Works
}

Checklist

  • [x] Documentation is updated (if required)
  • [ ] Tests are added/updated (if required)
  • [x] CHANGELOG entry is added (if required)

Cannedfood avatar Mar 09 '25 11:03 Cannedfood