Types of Comparison Operators
Operator | Description | Syntax Example | Output |
---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
< | Less than | 3 < 5 | true |
> | Greater than | 5 > 3 | true |
<= | Less than or equal to | 3 <= 3 | true |
>= | Greater than or equal to | 5 >= 5 | true |
Detailed Explanation
1. Equal to (==)
The == operator checks if two values are equal. It returns true if they are the same and false otherwise.
Syntax:
let result = value1 == value2;
Example:
fn main() {
let x = 10;
let y = 10;
println!("Is x equal to y? {}", x == y); // true
}
2. Not Equal to (!=
)
The != operator checks if two values are not equal. It returns true if the values are different.
Syntax:
let result = value1 != value2;
Example:
fn main() {
let x = 10;
let y = 5;
println!("Is x not equal to y? {}", x != y); // true
}
3. Less than (<)
The < operator checks if the left-hand operand is less than the right-hand operand.
Syntax:
let result = value1 < value2;
Example:
fn main() {
let x = 5;
let y = 10;
println!("Is x less than y? {}", x < y); // true
}
4. Greater than (>)
The > operator checks if the left-hand operand is greater than the right-hand operand.
Syntax:
let result = value1 > value2;
Example:
fn main() {
let x = 20;
let y = 10;
println!("Is x greater than y? {}", x > y); // true
}
5. Less than or Equal to (<=)
The <= operator checks if the left-hand operand is less than or equal to the right-hand operand.
Syntax:
let result = value1 <= value2;
Example:
fn main() {
let x = 10;
let y = 10;
println!("Is x less than or equal to y? {}", x <= y); // true
}
6. Greater than or Equal to (>=)
The >= operator checks if the left-hand operand is greater than or equal to the right-hand operand.
Syntax:
let result = value1 >= value2;
Example:
fn main() {
let x = 15;
let y = 10;
println!("Is x greater than or equal to y? {}", x >= y); // true
}
Practical Example: Using Comparison Operators in Decision-Making
Scenario: Check if a student passed an exam based on their score.
fn main() {
let score = 85;
let passing_score = 50;
if score >= passing_score {
println!("Congratulations! You passed.");
} else {
println!("You need to improve your score.");
}
}
Output:
Congratulations! You passed.