OneBite.Dev - Coding blog in a bite size

Check If Two Variable Not Equal In Rust

Code snippet for how to Check If Two Variable Not Equal In Rust with sample and detail explanation

Rust is a versatile programming language that combines the safety and high level of abstraction found in modern languages with the performance and control of traditional system programming languages. This article will guide you on how to check whether two variables are not equal in Rust.

Code snippet for checking if two variables are not equal in Rust

fn main() {
    let a = 5;
    let b = 10;

    if a != b {
        println!("The variables a and b are not equal.");
    } else {
        println!("The variables a and b are equal.");
    }
}

Code Explanation for checking if two variables are not equal in Rust

The above code snippet is quite straightforward and intuitive as it encompasses the basics of comparing variables in Rust. The main function begins the scope of our program.

We have two integer variables, ‘a’ which is set to 5, and ‘b’ which is set to 10. To ascertain whether these two variables are not equal, a conditional statement (if-else) is used.

The condition in the if-statement if a != b uses Rust’s inequality operator ‘!=’ to check if ‘a’ and ‘b’ are not equal. If the condition is true meaning ‘a’ and ‘b’ are not equal, it will print “The variables a and b are not equal.” Otherwise, it will print “The variables a and b are equal.”

The println! macro is then used for outputting the result. At runtime, if the condition specified within the if statement proves true, the message within the println! macro of the if branch will be printed. If the condition is false instead, the println! macro within the else branch will output its message. Thus in this example, since 5 is not equal to 10, the program will print: “The variables a and b are not equal.”

This simple comparison technique can be used across different data types in Rust allowing you to check for inequality among different variables.

rust