Sub topic 7
Unary operators: Neg and Not
This chapter assumes you know how to implement Add for a struct, what the Output associated type is, and how Copy affects operands that are passed by value.
Two traits, two operators
Rust has two overloadable prefix operators. Both traits live in std::ops.
| Operator | Trait | Method | Built-in meaning |
|---|---|---|---|
| `-x` | `Neg` | `fn neg(self) -> Self::Output` | Arithmetic negation of signed integers and floats |
| `!x` | `Not` | `fn not(self) -> Self::Output` | Logical NOT on `bool`, bitwise NOT on integers |
These traits are simpler than Add. They have no Rhs parameter because there is only one operand. They still have an Output type, so negating a value can produce a different type. In practice Output is almost always Self.
Implementing Neg and Not
The method takes self by value. As with binary operators, a Copy type stays usable after the call.
use std::ops::{Neg, Not};
#[derive(Debug, Clone, Copy, PartialEq)]
struct Vec2 {
x: f64,
y: f64,
}
impl Neg for Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
Vec2 { x: -self.x, y: -self.y }
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Switch {
On,
Off,
}
impl Not for Switch {
type Output = Switch;
fn not(self) -> Switch {
match self {
Switch::On => Switch::Off,
Switch::Off => Switch::On,
}
}
}
fn main() {
let v = Vec2 { x: 1.0, y: -2.0 };
assert_eq!(-v, Vec2 { x: -1.0, y: 2.0 });
assert_eq!(-(-v), v);
let s = Switch::On;
assert_eq!(!s, Switch::Off);
assert_eq!(!!s, s);
}The expression -v is sugar for Neg::neg(v), and !s is sugar for Not::not(s). Applying either operator twice should give back the original value. That is a good property to test.
Unary operators and references
The Neg and Not impls above take their operand by value. That is cheap for Copy types. For a type that owns heap data, -x would move x. As with Add, you can implement the trait for &T as well, so callers can write -&x and keep x.
use std::ops::Neg;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Neg for &Series {
type Output = Series;
fn neg(self) -> Series {
Series(self.0.iter().map(|x| -x).collect())
}
}
impl Neg for Series {
type Output = Series;
fn neg(self) -> Series {
-&self
}
}
fn main() {
let a = Series(vec![1.0, -2.0]);
let b = -&a;
assert_eq!(b, Series(vec![-1.0, 2.0]));
let c = -a;
assert_eq!(c, b);
}The by-value impl delegates to the reference impl, which keeps the logic in one place. Here -x works on &f64 because the standard library already implements Neg for references to numeric types.
Common mistakes
- Expecting
!to be logical for integers. Onu8,i32and the other integer types,!xflips every bit. Forboolit is logical NOT. If your type models a flag set, bitwise inversion is the natural meaning. - Negating unsigned types.
Negis not implemented foru32and its relatives, so-5u32does not compile. Your own wrapper around an unsigned value should not implementNegeither, unless theOutputis a signed type. - Surprising semantics. If
-xdoes something other than "the additive inverse", use a named method instead. For example,!on a set type could mean complement, but only when the universe of elements is clear.
Exercise
A type Celsius(f64) derives Clone, Copy, Debug, PartialEq. Write the impl that makes -Celsius(5.0) equal Celsius(-5.0). Why does the Output type not need a separate declaration for ! on a bool?
Show answer
Use use std::ops::Neg; then impl Neg for Celsius { type Output = Celsius; fn neg(self) -> Celsius { Celsius(-self.0) } }. The standard library already implements Not for bool with Output = bool, so the compiler resolves !flag through that existing impl and you declare nothing.