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:
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 2 | 12 |
/ | Division | 10 / 2 | 5 |
% | Remainder (modulo) | 10 % 3 | 1 |
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 (
f32orf64):
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).
| Operator | Description | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
< | Less than | 3 < 5 | true |
> | Greater than | 7 > 10 | false |
<= | Less than or equal to | 5 <= 5 | true |
>= | Greater than or equal to | 6 >= 5 | true |
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.
| Operator | Description | Example | Result |
|---|---|---|---|
&& | Logical AND | true && false | false |
| || | Logical OR | true || false | true |
! | Logical NOT | !true | false |
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.