5.5 Operators
Rust provides a set of operators similar to those in C/C++, with a few notable exceptions. For instance, Rust does not support the increment (++) or decrement (--) operators.
Type Consistency: Most binary operators require both operands to have the same type (e.g.,
1u8 + 2u32is invalid unless explicitly cast).
5.5.1 Unary Operators
- Negation (
-): Numeric negation (-x) - Boolean NOT (
!): Logical complement (!true == false) - Reference (
&): Creates a reference - Dereference (
*): Dereferences a pointer/reference
5.5.2 Binary Operators
- Arithmetic:
+,-,*,/,% - Comparison:
==,!=,>,<,>=,<= - Logical:
&&,|| - Bitwise:
&,|,^,<<,>>
When shifting signed values, Rust performs sign extension; unsigned types shift in zeros.
5.5.3 Assignment and Compound Operators
=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=
5.5.4 Ternary Operator
Rust does not have a ?: operator. Instead, you use an if expression:
#![allow(unused)] fn main() { let some_condition = true; let result = if some_condition { 5 } else { 10 }; }
5.5.5 Custom Operators and Operator Overloading
Rust does not allow the creation of new operator symbols. However, you can overload existing operators by implementing traits like Add, Sub, and so forth:
#![allow(unused)] fn main() { use std::ops::Add; struct Point { x: i32, y: i32 } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } } }
5.5.6 Operator Precedence
Rust’s operator precedence largely matches that of C/C++. Method calls and indexing have the highest precedence, while assignment is near the bottom. Parentheses can override the default precedence as usual.