prelude::ops
Every operator is a trait method: a + b is Add, a == b is Eq, a < b
is Lt, and format("%v", x) uses Show. The primitive types implement the
ones that make sense for them. Implement a trait for your own class or enum to
give it the operator:
class Money {
pub cents: int,
}
impl Add for Money {
pub fn add(Money a, Money b) -> Money {
return new Money(a.cents + b.cents);
}
}
Num and Integral bundle the arithmetic traits so generic code can ask for
“any number” (fn sum<T: Num>(…)). #[derive(Eq, Ord, Show)] writes the
common instances for you; see Macros. The rules for
each operator are in Operators.
Built into the compiler.
Traits#
| Name | Description |
|---|---|
Add | The addition operator +. |
Sub | The subtraction operator -. |
Mul | The multiplication operator *. |
Div | The division operator /. |
Neg | The unary negation operator -x. |
Rem | The remainder operator %. |
Pow | The exponentiation operator **. |
Num | The numeric bundle: Add, Sub, Mul, Div, Neg, Rem and Pow. |
Shl | The left shift operator <<. |
Shr | The right shift operator >>. |
BitAnd | The bitwise AND operator &. |
BitOr | The bitwise OR operator |. |
BitXor | The bitwise XOR operator ^. |
BitNot | The bitwise NOT operator ~x. |
Integral | The integer bundle: Num plus Shl, Shr, BitAnd, BitOr, BitXor and BitNot. |
Eq | The equality operators == and !=. |
Ord | The ordering bundle: Lt, Le, Gt and Ge, with Eq. |
Lt | The less-than operator <. |
Le | The less-or-equal operator <=. |
Gt | The greater-than operator >. |
Ge | The greater-or-equal operator >=. |
Show | Conversion to a display string, used by the %v format specifier. |
Length | A size query: x.len(). |
Into | Conversion from S into T, written impl Into<T> for S. |