0
0
Rustprogramming~5 mins

Relational operators in Rust

Choose your learning style9 modes available
Introduction

Relational operators help us compare two values to see how they relate, like if one is bigger or smaller than the other.

Checking if a number is greater than another to decide what to do next.
Comparing ages to see who is older.
Finding out if two values are equal before continuing a task.
Making sure a score is less than a limit before allowing a player to continue.
Deciding if a temperature is within a safe range.
Syntax
Rust
value1 < value2
value1 > value2
value1 <= value2
value1 >= value2
value1 == value2
value1 != value2

Use == to check if two values are equal.

Use != to check if two values are not equal.

Examples
This checks if a is less than b. It is true because 5 is less than 10.
Rust
let a = 5;
let b = 10;
let result = a < b; // true
This checks if x is equal to y. It is true because both are 7.
Rust
let x = 7;
let y = 7;
let result = x == y; // true
This checks if m is not equal to n. It is true because 3 is not 8.
Rust
let m = 3;
let n = 8;
let result = m != n; // true
Sample Program

This program checks if a person is old enough to enter by comparing age with limit. It also prints if the score is passing by comparing score with passing_score.

Rust
fn main() {
    let age = 20;
    let limit = 18;

    if age >= limit {
        println!("You are allowed to enter.");
    } else {
        println!("You are not allowed to enter.");
    }

    let score = 85;
    let passing_score = 60;

    println!("Did you pass? {}", score >= passing_score);
}
OutputSuccess
Important Notes

Relational operators always return a boolean: true or false.

Use parentheses to group comparisons if combining with other operators.

Summary

Relational operators compare two values and return true or false.

Common operators: <, >, <=, >=, ==, !=.

They help make decisions in your program based on value comparisons.