This "==" and "!=" is have different behaviours?

I happened to be writing a code with a while loop, the question is why when I replace != 10 with == 10, the output doesn't display the printed text that should be there.

fn main(){
    let mut s = 1;
// This is using ==
    while s == 10 {
        println!("s: {s}");
        s +=1;

Output :

Compiling variables v0.1.0 (/home/qoori/Documents/Rust/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.36s
     Running `target/debug/variables`
 *  Terminal will be reused by tasks, press any key to close it. 

Changed to != 10

while s != 10 


s: 2
s: 3
s: 4
s: 5
s: 6
s: 7
s: 8
s: 9

the while loop continue if the condition is true


!= means not equal , == means equal , they do have different behaviours


When the condition of you while loop s == 10 is evaluated, s equals 1. The condition returns false, because 1 does not equal 10. When the condition of a while loop is evaluated as false, the loop is exited. The condition is evaluated before the loop body is executed, which is why you don't see a single print statement from that loop. From the docs:

The while expression runs the conditional expression before running the loop body, then runs the loop body if the conditional expression evaluates to true, or exits the loop otherwise.

The != (not equal) operator checks whether s does not equal 10. It basically has the opposite behaviour of ==, returning false where == returns true and true where == returns false[1]. As s equals 1 when you enter the while loop and s != 10 is evaluated, s = 1 does not equal 10. s != 10 evaluates as true, so you enter the loop body, where you increment s to 2. 2 still doesn't equal 10, so when s != 10 is evaluated before the second iteration of your while loop, it still returns true. So you enter the loop body again. This goes on till s equals 10 and s != 10 returns false. Then the loop has finished and your program continues.

  1. For (almost all?) types. Theoretically you can change the behaviour of the != operator for a type by implementing the PartialEq::ne method for it, changing the default behaviour I described above. ↩ī¸Ž


Why would you expect != and == to do the same thing?

To me, the questions reads like "why do 5+10 and 5*10 give different answers?", to which the only answer is "well they're different things so that's usually the case"...


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.