5.6 Operators

Rust provides a set of operators similar to those in C/C++, with a few notable exceptions. For example, Rust does not support the increment (++) or decrement (--) operators.

Type Consistency: Most binary operators require both operands to have the same type. For instance, 1u8 + 2u32 is invalid unless you explicitly cast.

5.6.1 Unary Operators

  • Negation (-): Numeric negation (-x)
  • Boolean NOT (!): Logical complement (!true == false)
  • Reference (&): Creates a reference
  • Dereference (*): Dereferences a pointer or reference

5.6.2 Binary Operators

  • Arithmetic: +, -, *, /, %
  • Comparison: ==, !=, >, <, >=, <=
  • Logical: &&, ||
  • Bitwise: &, |, ^, <<, >>

When shifting signed values, Rust performs sign extension. Unsigned types shift in zeros.

5.6.3 Assignment and Compound Operators

  • =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

5.6.4 Ternary Operator

Rust does not have the C-style ?: operator. Instead, you use an if expression:

#![allow(unused)]
fn main() {
let some_condition = true;
let result = if some_condition { 5 } else { 10 };
}

5.6.5 Custom Operators and Operator Overloading

Rust does not allow the creation of new operator symbols, but you can overload existing ones by implementing traits like Add, Sub, and so on:

#![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.6.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. As usual, parentheses can override the default precedence.