Rust Basic Operators

Rust provides a set of operators that allow you to perform arithmetic, comparison, and logical operations. Operators are the building blocks of most programs, and understanding them is essential for writing effective Rust code.

In this tutorial, we’ll explore the most commonly used operators in Rust with examples.

Arithmetic Operators #

Arithmetic operators are used to perform mathematical calculations. Rust supports all the usual operators you would expect:

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 212
/Division10 / 25
%Remainder (modulo)10 % 31

Arithmetic Operator Example #

fn main() {
    let a = 10;
    let b = 3;

    println!("Addition: {}", a + b);
    println!("Subtraction: {}", a - b);
    println!("Multiplication: {}", a * b);
    println!("Division: {}", a / b);   // Integer division, result = 3
    println!("Remainder: {}", a % b);
}
Code language: JavaScript (javascript)

⚠️ Note:

  • Division with integers truncates the result (no decimals).
  • To get a floating-point result, use floating-point numbers (f32 or f64):
let x = 10.0;
let y = 3.0;
println!("Floating-point division: {}", x / y); // 3.333...Code language: JavaScript (javascript)

Comparison Operators #

Comparison operators are used to compare two values. These expressions always return a Boolean (true or false).

OperatorDescriptionExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
<Less than3 < 5true
>Greater than7 > 10false
<=Less than or equal to5 <= 5true
>=Greater than or equal to6 >= 5true

Comparison Operator Example #

fn main() {
    let a = 7;
    let b = 10;

    println!("a == b: {}", a == b);
    println!("a != b: {}", a != b);
    println!("a < b: {}", a < b);
    println!("a > b: {}", a > b);
    println!("a <= b: {}", a <= b);
    println!("a >= b: {}", a >= b);
}Code language: Rust (rust)

Logical Operators #

Logical operators are used to combine Boolean expressions.

OperatorDescriptionExampleResult
&&Logical ANDtrue && falsefalse
||Logical ORtrue || falsetrue
!Logical NOT!truefalse

Logical Operator Example #

fn main() {
    let x = true;
    let y = false;

    println!("x AND y: {}", x && y);   // false
    println!("x OR y: {}", x || y);    // true
    println!("NOT x: {}", !x);         // false
}
Code language: Rust (rust)

You can combine arithmetic, comparison, and logical operators to build powerful expressions. In the next lessons, you’ll use them inside control flow statements (if, loop, while, for) to build real logic in your programs.

Summary #

  • Arithmetic operators (+, -, *, /, %) let you perform mathematical calculations.
  • Comparison operators (==, !=, <, >, <=, >=) return Boolean values.
  • Logical operators (&&, ||, !) allow combining conditions.
  • Rust enforces type safety, so operators only work between compatible types.
Was this Helpful ?