Why can't I use the value in the vector for comparative operation?

Declares vector v with values 1,2,3,4.

let v: Vec = [1,2,3,4].to_vec();

Codes that compare the entire vector to other vectors or arrays operate without errors.

let ans = v == [1,2,3,4];
println!("{}",ans) ; // print "true"

However, when I attempt to compare the internal values of a vector, an error occurs because the reference to the vector is compared to an integer. How can I solve this problem?

let ans = &v[1] == 0; // it makes error
println!("{}",ans);

Let's assume this code:

fn main() {
    let v = vec![1, 2, 3, 4];
    let ans = &v[1] == 0;
    println!("{}", ans);
}

Why do you think, that you need &v[1]? The compiler gives a nice error about this:

error[E0277]: can't compare `&{integer}` with `{integer}`

You see, that you are trying to compare a &... with .... An intuitive guess would be to remove the & and see: it works :wink:

fn main() {
    let v = vec![1, 2, 3, 4];
    let ans = v[1] == 0;
    println!("{}", ans); // prints false
}
1 Like

Thank you. I was mistaken.

In the future, please format your code by adding three backticks (```) to the beginning and the end:

```
put your code here
```

so that the code gets highlighted.

See our pinned topic for more information:

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.