Crate ref_ops

Source
Expand description

An escape hatch for implementing ops traits for references to newtypes.

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

use core::ops::Neg;

struct A<T>(T);

impl<'a, T> Neg for &'a A<T>
where
    &'a T: Neg,
{
    type Output = A<<&'a T as Neg>::Output>;

    fn neg(self) -> Self::Output {
        A(-&self.0)
    }
}

fn f<T>(a: T)
where
    for<'a> &'a T: Neg,
{
    let minus_a = -&a;

    // to do something with `a` and `minus_a`
}

fn g<T>(a: T)
where
    for<'a> &'a T: Neg,
{
    f(a);
}

but the following code does:

use core::ops::Neg;
use ref_ops::RefNeg;

struct A<T>(T);

impl<T> Neg for &A<T>
where
    T: RefNeg,
{
    type Output = A<T::Output>;

    fn neg(self) -> Self::Output {
        A(self.0.ref_neg())
    }
}

fn f<T>(a: T)
where
    for<'a> &'a T: Neg,
{
    let minus_a = -&a;

    // to do something with `a` and `minus_a`
}

fn g<T>(a: T)
where
    for<'a> &'a T: Neg,
{
    f(a);
}

Traits§

RefAdd
add operation through references.
RefBitAnd
bitand operation through references.
RefBitOr
bitor operation through references.
RefBitXor
bitxor operation through references.
RefDiv
div operation through references.
RefMul
mul operation through references.
RefMutAdd
add operation through mutable references.
RefMutBitAnd
bitand operation through mutable references.
RefMutBitOr
bitor operation through mutable references.
RefMutBitXor
bitxor operation through mutable references.
RefMutDiv
div operation through mutable references.
RefMutMul
mul operation through mutable references.
RefMutNeg
neg operation through mutable references.
RefMutNot
not operation through mutable references.
RefMutRem
rem operation through mutable references.
RefMutShl
shl operation through mutable references.
RefMutShr
shr operation through mutable references.
RefMutSub
sub operation through mutable references.
RefNeg
neg operation through references.
RefNot
not operation through references.
RefRem
rem operation through references.
RefShl
shl operation through references.
RefShr
shr operation through references.
RefSub
sub operation through references.