Expand description
An escape hatch for implimenting
Neg
for references to newtypes.
As of Rust 1.52.1, the following code does not compile:
ⓘ
use core::ops::Neg;
#[derive(PartialEq)]
struct A<T>(T);
impl<'a, T> Neg for &'a A<T>
where
T: Neg,
&'a T: Neg<Output = T::Output>,
{
type Output = A<T::Output>;
fn neg(self) -> Self::Output {
A(self.0.neg())
}
}
fn f<T>(a: T)
where
for<'a> &'a T: Neg,
{
let neg_a = (&a).neg();
// to do something with `a` and `neg_a`
todo!();
}
fn g<T>(a: T)
where
for<'a> &'a T: Neg,
{
f(a);
}
assert!(-&A(1.0) == A(-1.0));but the following code does:
use core::ops::Neg;
use ref_ops::RefNeg;
#[derive(PartialEq)]
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 neg_a = (&a).neg();
// to do something with `a` and `neg_a`
todo!();
}
fn g<T>(a: T)
where
for<'a> &'a T: Neg,
{
f(a);
}
assert!(-&A(1.0) == A(-1.0));