Trait ref_ops::RefSub[][src]

pub trait RefSub<Rhs>: Sub<Rhs> {
    fn ref_sub(&self, other: Rhs) -> Self::Output;
}
Expand description

An escape hatch for implimenting Sub for references to newtypes.

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

use core::ops::Sub;

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

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

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

pub fn f<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Sub<&'b U>,
{
    let a_b = (&a).sub(&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: Sub<&'b U>,
{
    f(a, b);
}

assert!(&A(3.0) - &A(1.0) == A(2.0));

but the following code does:

use core::ops::Sub;
use ref_ops::RefSub;

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

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

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

pub fn f<T, U>(a: T, b: U)
where
    for<'a, 'b> &'a T: Sub<&'b U>,
{
    let a_b = (&a).sub(&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: Sub<&'b U>,
{
    f(a, b);
}

assert!(&A(3.0) - &A(1.0) == A(2.0));

Required methods

Implementors