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

  • add operation through references.
  • bitand operation through references.
  • bitor operation through references.
  • bitxor operation through references.
  • div operation through references.
  • mul operation through references.
  • add operation through mutable references.
  • bitand operation through mutable references.
  • bitor operation through mutable references.
  • bitxor operation through mutable references.
  • div operation through mutable references.
  • mul operation through mutable references.
  • neg operation through mutable references.
  • not operation through mutable references.
  • rem operation through mutable references.
  • shl operation through mutable references.
  • shr operation through mutable references.
  • sub operation through mutable references.
  • neg operation through references.
  • not operation through references.
  • rem operation through references.
  • shl operation through references.
  • shr operation through references.
  • sub operation through references.