Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error with % operator inside closure

Tags:

rust

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) {
like image 335
tez Avatar asked Jul 07 '15 05:07

tez


1 Answers

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)
like image 185
Vladimir Matveev Avatar answered Sep 21 '22 16:09

Vladimir Matveev