Sub topic 7
Unary operators: Neg and Not
This chapter assumes you know how to implement a trait on a struct, how associated types work, and how Copy differs from a move. It also assumes you have seen impl Add for Vec2 from the earlier chapters. Unary operators follow the same pattern as binary ones, with one operand and no Rhs parameter.
The two overloadable unary operators
Rust has three prefix operators: -, ! and *. Two of them are overloaded through std::ops traits that look alike.
| Expression | Trait | Method | Typical meaning |
|---|---|---|---|
| `-a` | `Neg` | `fn neg(self) -> Self::Output` | arithmetic negation |
| `!a` | `Not` | `fn not(self) -> Self::Output` | logical or bitwise complement |
The third operator, *, is the dereference operator. It belongs to Deref and DerefMut, which have different rules and are not covered here.
Each trait has no type parameters and one associated type, Output. The method takes self by value, so a unary operator consumes its operand just as Add does. A trait with no Rhs parameter means you get exactly one impl per type, unlike Mul<f64> and Mul<Vec2>, which can coexist.
Implementing Neg
Neg for a vector type negates each component. The type derives Copy, so the operand stays usable after the call.
use std::ops::Neg;
#[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 }
}
}
fn main() {
let v = Vec2 { x: 1.0, y: -2.0 };
assert_eq!(-v, Vec2 { x: -1.0, y: 2.0 });
assert_eq!(Neg::neg(v), -v);
assert_eq!(-(-v), v);
}The body uses -self.x, which is itself a call to Neg for f64. Unary operators on your own types are usually built from the same operators on the fields.
Output is usually Self, but it does not have to be. A Neg impl could return a different type, for example a signed type for an unsigned wrapper. The compiler takes the type of -v from <Vec2 as Neg>::Output. If you leave out type Output, you get error E0046 (missing trait item).
Negating references
Operators take their operand by value, so -v on a non-Copy type moves v. Callers often hold a borrowed value, and cloning it first is wasteful. The fix is the same as for Add: implement the trait for &T as well as T.
use std::ops::Neg;
#[derive(Debug, Clone, PartialEq)]
struct Series(Vec<f64>);
impl Neg for Series {
type Output = Series;
fn neg(mut self) -> Series {
for v in &mut self.0 {
*v = -*v;
}
self
}
}
impl Neg for &Series {
type Output = Series;
fn neg(self) -> Series {
Series(self.0.iter().map(|v| -v).collect())
}
}
fn main() {
let s = Series(vec![1.0, -2.0, 3.0]);
let negated = -&s;
assert_eq!(negated, Series(vec![-1.0, 2.0, -3.0]));
// `s` is still usable because only a reference was consumed.
assert_eq!(s.0.len(), 3);
let back = -negated;
assert_eq!(back, s);
}The two impls do different work on purpose:
- The by-value impl owns its operand, so it reuses the buffer and negates in place. It allocates nothing.
- The reference impl cannot mutate, so it builds a new
Vec.
Notice -v inside .map(|v| -v). Here v is a &f64, and the standard library implements Neg for &f64, so the closure compiles.
For a Copy type like Vec2, a reference impl is a one-liner that dereferences and reuses the value impl:
impl Neg for &Vec2 {
type Output = Vec2;
fn neg(self) -> Vec2 {
-*self
}
}This works only when the type is Copy. For other types, write the logic against borrowed data as shown above.
Implementing Not
Not is the complement operator. On bool it is logical negation. On integers it flips every bit. A user type should pick whichever meaning matches its domain. Two common uses are flag sets and two-state enums.
use std::ops::Not;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Permissions(u8);
impl Permissions {
const READ: Permissions = Permissions(0b001);
const WRITE: Permissions = Permissions(0b010);
const EXEC: Permissions = Permissions(0b100);
const ALL: Permissions = Permissions(0b111);
}
impl Not for Permissions {
type Output = Permissions;
fn not(self) -> Permissions {
// Mask with ALL so that unused high bits stay zero.
Permissions(!self.0 & Self::ALL.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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() {
assert_eq!(!Permissions::READ, Permissions(0b110));
assert_eq!(!!Permissions::WRITE, Permissions::WRITE);
assert_eq!(!Permissions::ALL, Permissions(0));
assert_eq!(!Switch::On, Switch::Off);
}The mask in Permissions::not matters. Without it, !READ would be 0b1111_1110, which sets five bits that mean nothing. A complement over a type that uses only some of its bits should stay inside the valid range.
Behaviour of the built-in impls
Your impls sit alongside the standard ones, and generic code often relies on them.
Negis implemented for signed integers (i8toi128,isize) and forf32andf64. It is not implemented for unsigned integers, so-1u32is a compile error (E0600).- Overflow applies to signed integers.
-i32::MINdoes not fit ini32. In a debug build this panics, and a constant expression is rejected at compile time by thearithmetic_overflowlint. If the input may beMIN, usechecked_neg, which returnsNone. Notis implemented forbooland every integer type, signed and unsigned.- Both traits are implemented for references to these types, such as
&f64and&bool.
fn main() {
assert_eq!(i32::MIN.checked_neg(), None);
assert_eq!(5i32.checked_neg(), Some(-5));
assert_eq!(!0u8, 255);
assert_eq!(!true, false);
}Precedence
Unary operators bind tighter than every binary operator, but looser than method calls and field access. The method-call rule catches people out with numeric literals.
fn main() {
let a = -2.0_f64.powi(2);
assert_eq!(a, -4.0); // parsed as -(2.0_f64.powi(2))
let b = (-2.0_f64).powi(2);
assert_eq!(b, 4.0);
}The same ordering applies to your own types. In -v.length(), the method call runs first, and Neg applies to the result. If length returns an f64, you are negating a float, not calling Neg for Vec2. Add parentheses whenever the intent is not obvious.
Using the traits in generic code
A bound on Neg lets one function work across integers, floats and your own types. As with Add, name the output type so the result is useful.
use std::ops::Neg;
fn negate_all<T>(items: &[T]) -> Vec<T>
where
T: Copy + Neg<Output = T>,
{
items.iter().map(|&x| -x).collect()
}
fn main() {
assert_eq!(negate_all(&[1, -2, 3]), vec![-1, 2, -3]);
assert_eq!(negate_all(&[0.5, -1.5]), vec![-0.5, 1.5]);
}A bound on the reference form is harder to write because it needs a higher-ranked lifetime: for<'a> &'a T: Neg<Output = T>. Use it only when you must avoid Copy and cloning. Most code is simpler with T: Copy.
Common errors
- Using a value after negating it. For a non-
Copytype,-smovess. The compiler reports "use of moved value". ImplementNeg for &Tand write-&s, or deriveCopyif the type is small. - Missing
Output. Every impl needstype Output = ...;, and the method's return type must match it. - Expecting
Notto work as a logical not on a non-boolcondition.if !xrequiresx: bool, or a type whoseNot::Outputisbool. - Negating an unsigned type. Convert first (
-(x as i64)), or use a signed type. - Surprising semantics. Making
-accountor!userdo something other than negate or complement hides behaviour behind a symbol. Prefer a named method for anything that is not clearly negation or complement.
Exercise
A type Celsius(f64) derives Clone but not Copy. You implement Neg for Celsius only. Given let t = Celsius(20.0); let u = -t; println!("{:?}", t);, why does this fail to compile, and what is the smallest change that makes - work on a borrowed value without cloning?
Show answer
-t calls Neg::neg(t), which takes self by value. Because Celsius is not Copy, this moves t, so the later use in println! reports a use of a moved value. Add impl Neg for &Celsius { type Output = Celsius; fn neg(self) -> Celsius { Celsius(-self.0) } } and write -&t. Only the reference is consumed, so t remains usable.
Exercise
You implement Not for Permissions(u8) as Permissions(!self.0) with no mask, where only the low three bits are meaningful. What does !Permissions(0b001) produce, and why is it a problem?
Show answer
It produces Permissions(0b1111_1110). Five bits that carry no meaning are now set, so equality checks against Permissions(0b110) fail, and later bitwise operations may see flags that do not exist. Mask the result with the valid bits, as in !self.0 & 0b111.