Start learning free

LESSON 72 OF 348 · CONDITIONAL STATEMENTS

Comparison Operators in Rust in Rust

Lesson

When writing if statements, we usually compare two values using one or more comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

For example:

10 == 10 // Evaluates to true
3 < 2 // Evaluates to false
15 >= 15 // Evaluates to true
17 != 12 // Evaluates to true

We usually use these operators with variables:

let a = 10;
let b = 15;

if a == b {
    println!("a is equal to b");
}
if a < b {
    println!("a is less than b");
}

The first condition is not satisfied since 10 == 15 evaluates to false.

The second condition is satisfied since 10 < 15 evaluates to true.

The code above prints "a is less than b".


Assignment
Follow the Coding Tutorial and let's play with comparison operators.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    Comparison Operators in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free