Rust Reference ยท Standard Library Modules
The std::ops module
Reference for Rust std::ops: Add, Sub, Mul, Neg, Not, Index, Deref, Drop, the Fn traits, range types, RangeBounds and ControlFlow, with examples.
std::ops is where operators live. Each overloadable operator corresponds to a trait: + is Add, - is Sub, unary - is Neg, ! is Not, a[i] is Index, *a is Deref, and so on. Implementing the trait on your type is how you make the operator work for it. The module also holds Drop, the closure traits Fn, FnMut and FnOnce, all the range types, and ControlFlow.
Operators on the primitive types are built in, but they are described by the same traits, so generic code can say T: Add<Output = T>.
use std::ops::Add; fn sum2<T: Add<Output = T>>(a: T, b: T) -> T { a + b }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
| Operator | Trait | Method |
|---|---|---|
a + b, a - b, a * b, a / b, a % b |
Add, Sub, Mul, Div, Rem |
add, sub, mul, div, rem |
a & b, a | b, a ^ b, a << b, a >> b |
BitAnd, BitOr, BitXor, Shl, Shr |
bitand, bitor, bitxor, shl, shr |
-a, !a |
Neg, Not |
neg, not |
a += b and the other compound forms |
AddAssign, SubAssign, ... |
add_assign, ... |
a[i] |
Index, IndexMut |
index, index_mut |
*a |
Deref, DerefMut |
deref, deref_mut |
| call syntax | Fn, FnMut, FnOnce |
closures only (implementing them by hand is unstable) |
| scope exit | Drop |
drop |
Range types: Range (a..b), RangeInclusive (a..=b), RangeFrom (a..), RangeTo (..b), RangeToInclusive (..=b), RangeFull (..). Helpers: RangeBounds, Bound, ControlFlow.
Usage notes
- Operators take operands by value. For non-
Copytypes, implement the trait for references too (impl Add for &Matrix) to avoid forcing clones. a == banda < bare not here; they belong tostd::cmp(PartialEq,PartialOrd).&&and||cannot be overloaded.Outputis an associated type, soMul<f64> for VandMul<V> for Vcan coexist with different outputs.- Compound assignment is separate from the plain operator; implement both if you want
a += banda + b. Derefcoercion lets&Stringact as&strand&Box<T>as&T. Use it for smart pointers, not as a stand-in for inheritance.Dropcannot be called directly (x.drop()is an error); usestd::mem::drop(x).Rangeis an iterator (Range<usize>), whileRangeInclusivestores an extra exhausted flag. Ranges are notCopyfor that reason.ControlFlowmodels early exit intry_foldandtry_for_eachwithout allocating an error.- The
Trytrait behind?is not yet stable, so custom types cannot be used with?on stable Rust.