Comparison Operators

What Are Comparison Operators?

Comparison Operators are used for comparing the values of two operands.

Types

Below is the list of comparison operators in Rust.

operatoroperationexplanation
operand1 > operand2greater thenEvaluates to true if operand 1 is greater then Operand 2
operand1 < operand2lesser thenEvaluates to true if operand 1 is lesser then Operand 2
operand1 <= operand2less then equal toEvaluates to true if operand 1 is lesser or equal to the Operand 2
operand1 >= operand2greater then equal toEvaluates to true if operand 1 is greater or equal to the Operand 2
operand1 == operand2equal toEvaluates to true if operand 1 equal to the Operand 2
operand1 != operand2Not equal toEvaluates to true if operand 1 not equal to the Operand 2

The following example shows the use of comparison operators in a program:

  fn main() {
    let a = 2;
    let b = 3;
    println!("Operand 1:{}, Operand 2:{}", 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);
    println!("a != b:{}", a != b);
}
  

output:-

  Operand 1:2, Operand 2:3
a > b:false
a < b:true
a >= b:false
a <= b:true
a == b:false
a != b:true
  

Quiz

Test your understanding of comparison operators in Rust!

--- primaryColor: steelblue secondaryColor: '#e8e8e8' textColor: black shuffleQuestions: false shuffleAnswers: true locale: en --- Test your understanding of comparison operators in Rust! # What is the output of the following code? ``` fn main() { let mut a = true; let mut b = true; a = a > b && b < a; b = !b; println!("a: {}", a); println!("b: {}", b); } ``` - [ ] ``` a: false b: true ``` - [ ] ``` a: true b: false ``` - [ ] ``` a: true b: true ``` - [ ] ``` a: false b: false ```

Last updated 25 Jan 2024, 05:11 +0530 . history