0
fn count_occur(v: &Vec<i32>, val: i32) -> usize {
    v.into_iter().filter(|&&x| x == val).count()
}

fn main() -> () {
    let v1 : Vec<i32> = vec![1,2,3, 4,5,6];
    for &item in &v1 {
        count_occur(&v1, item);
    }  
}

Can someone explain me why does lambda need to take &&x (I mean why double reference is necessary - I cannot see why an element passed to the lambda is a reference to a reference)

J. Doe
  • 65
  • 6
  • 1
    Related: https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-or – hellow Jul 15 '19 at 10:47
  • 1
    Btw: It is bad pratice to write `-> ()`, because returning the unit type is the default and you don't need to expliclty write it. See https://rust-lang.github.io/rust-clippy/master/index.html#unused_unit – hellow Jul 15 '19 at 10:48
  • 2
    There's a twist here not covered in the duplicate -- the resolution of the`into_iter()` method. There's a separate implementation of `IntoIterator` for `&Vec`, which calls`iter()` on the vector, so the item type is `&T`. – Sven Marnach Jul 15 '19 at 12:54

1 Answers1

0

IntoIterator implementation for &'a Vec is returning items of &T.

filter's predicate is defined as where P: FnMut(&I::Item) -> bool. It's taking a reference to the iterator's item, hence the double reference.

idursun
  • 6,261
  • 1
  • 37
  • 51