Search code examples
rusttype-mismatch

error: type mismatch: expected `usize`, found `i64` with a `Vec<i64>`


fn main() {
    let mut a: Vec<i64> = Vec::new();

    let n = 42;
    a.push(n);

    let i = 0;
    a[i];

    let j = n;

    i == j;
}

I am not able to fix type mismatch in rust, error says:

error[E0308]: mismatched types
 --> src/main.rs:4:10
  |
4 |     i == j;
  |          ^ expected usize, found i64

Solution

  • The error message is saying that you cannot compare i (type usize) and j (type i64).

    Why is i type usize? Because you're using it as an index in a[i].

    Why is j type i64? Because you've initialised it from n, which has type i64 because it is pushed into a Vec<i64>.

    Why can you not compare the two? Because in languages where you can, that would be done by either converting usize to i64 and then performing the comparison, or by converting i64 to usize and then performing the comparison. Both approaches can potentially do the wrong thing.