This code
let vec = vec![1, 3, 4, 5, 6];
for i in vec.iter().filter(|x| x % 2 == 0) {
println!("{}", i);
}
Produces the error
<anon>:4:36: 4:37 error: binary operation `%` cannot be applied to type `&&_` [E0369]
<anon>:4 for i in vec.iter().filter(|x| x % 2 == 0) {
^
I cannot understand the meaning of this error. Is this related to how the anonymous closure structure is created by the compiler?
The following code seems to be working.
for i in vec.iter().filter(|&x| x % 2 == 0) {
No, it is not related to how closure structure is created, it is a simple type error.
vec.iter()
, when vec: Vec<T>
, returns an iterator which yields references to its elements. filter()
closure also accepts each element by reference (because otherwise elements would be consumed but this would defeat the whole purpose of filter()
). Therefore, in vec.iter().filter(|x| ...)
the closure argument x
has type &&T
, in your case, &&i32
.
Rust numeric operators can't be applied to &&T
, only to &T
or T
, so you need to dereference the closure argument somehow. There are two ways, first, as you noticed, you can use dereference pattern:
vec.iter().filter(|&x| x % 2 == 0)
// or even
vec.iter().filter(|&&x| x % 2 == 0)
Dereference pattern automatically dereferences the reference it is matching:
&x: &&i32 ==> x: &i32
&&x: &&i32 ==> x: i32
Alternatively, you can dereference the number directly:
vec.iter().filter(|x| *x % 2 == 0)
// or
vec.iter().filter(|x| **x % 2 == 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With