Trait ref_ops::RefMul[][src]

pub trait RefMul<Rhs>: Mul<Rhs> {
    fn ref_mul(&self, other: Rhs) -> Self::Output;
}
Expand description

An escape hatch for implimenting Mul for references to newtypes.

As of Rust 1.52.1, the following code does not compile:

use core::ops::Mul;

#[derive(PartialEq)]
struct A<T>(T);

impl<'a, 'b, T, U> Mul<&'b A<U>> for &'a A<T>
where
    T: Mul<&'b U>,
    &'a T: Mul<&'b U, Output = T::Output>,
{
    type Output = A<T::Output>;

    fn mul(self, other: &'b A<U>) -> Self::Output {
        A(self.0.mul(&other.0))
    }
}

pub fn f<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Mul<&'b U>,
{
    let a_b = (&a).mul(&b);

    // to do something with `a`, `b`, and `a_b`
    todo!();
}

pub fn g<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Mul<&'b U>,
{
    f(a, b);
}

assert!(&A(2.0) * &A(3.0) == A(6.0));

but the following code does:

use core::ops::Mul;
use ref_ops::RefMul;

#[derive(PartialEq)]
struct A<T>(T);

impl<'a, T, U> Mul<&'a A<U>> for &A<T>
where
    T: RefMul<&'a U>,
{
    type Output = A<T::Output>;

    fn mul(self, other: &'a A<U>) -> Self::Output {
        A(self.0.ref_mul(&other.0))
    }
}

pub fn f<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Mul<&'b U>,
{
    let a_b = (&a).mul(&b);

    // to do something with `a`, `b`, and `a_b`
    todo!();
}

pub fn g<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Mul<&'b U>,
{
    f(a, b);
}

assert!(&A(2.0) * &A(3.0) == A(6.0));

Required methods

Implementors