rustreferenceiteratorclosuresownership

Why the closure passed to map() does not take a reference while the one passed to filter() takes a reference?


The closure passed to map() does not take a reference while the one passed to filter() takes a reference in Rust. Most of the iterator adapters take a reference. Is there any reason why map() does not take a reference in Rust?

let a = (0..3).map(|x| x*2);
for i in a {
    println!("map i = {}", i);
}

let a = (0..3).filter(|&x| x % 2 == 0);
for i in a {
    println!("filter i = {}", i);
}

Solution

  • .map(<closure>) and .filter(<closure>) have different uses.

    .map(<closure>) gives ownership of the iterator's elements to the closure so they can be transformed into new elements, which are then returned by the closure.

    However, .filter(<closure>) returns the original elements when the closure predicate evaluates to true. Thus, it can't give away ownership of the elements to the closure, so it must pass the elements by reference.