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);
hellow
August 4, 2020, 7:28am
2
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
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.
L.F
August 4, 2020, 1:20pm
4
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:
To format code in this forum you need to surround the code with three backticks (```). For example, typing this...
```
fn main() {
println!()
}
```
...will be rendered as highlighted Rust code, like so:
fn main() {
println!()
}
You can also tell the forum software which language you're using by adding the language after the opening backticks.
```cpp
#include <iostream>
int main() {
std::cout << "Hello World!";
}
```
Will appear with highlighting as:
#include <iostream>
int main(…
system
Closed
November 2, 2020, 1:20pm
5
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.