Expected error mismatch between "rustc" and "cargo"

Hi, I am new to Rust. I was practicing the following example from the book (3.5). As per the logic it should not get compiled. And it does not get compiled only in Cargo because of type mismatch in expression but in rustc I do not get any error and the program also works fine after compilation.

fn main() {
let condition = true;

let number = if condition { 5 } else { "six" };

println!("The value of number is: {number}");

}

Additional info (System windows 11, processor AMD 3950x )-
D:\Rust\p_20241118>rustc --version
rustc 1.82.0 (f6e511eec 2024-10-15)

D:\Rust\p_20241118>cargo --version
cargo 1.82.0 (8f40fc59f 2024-08-21)

D:\Rust\p_20241118>

Are you sure? That isn't valid Rust code. I get an error:

$ rustc src/main.rs 

error[E0308]: `if` and `else` have incompatible types
 --> src/main.rs:4:44
  |
4 |     let number = if condition { 5 } else { "six" };
  |                                 -          ^^^^^ expected integer, found `&str`
  |                                 |
  |                                 expected because of this

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

Yes, this is not valid at "if condition { 5 } else { "six" }" part because of i32 and string use with if, so it is a type mismatch. But this does not give error when we compiled with "rustc" that is surprising from me. As expected it gives error in "cargo".

Please see the following terminal output. I changed the values "condition = true" and "condition = false". And it worked both time with "rustc"

D:\Rust\p_20241112>rustc main.rs

D:\Rust\p_20241112>.\main.exe
The value of number is: 5

D:\Rust\p_20241112>rustc main.rs

D:\Rust\p_20241112>.\main.exe
The value of number is: six

That isn't possible. The code in OP cannot type check. See my terminal output above where I ran rustc (like you have) and it failed.

You have something else going on. Maybe the string "5" instead of numeric 5.

2 Likes

Thanks, yes, I had entered 5 as a string by enclosing it in "". Whereas in the other one, I had copied and pasted the entire block of code, so it did not throw the error. Thanks again.

I will be more careful from the next time onwards.

This is something to keep in mind for the future: a common source of confusing problems is not actually running the exact code that you think you're running.