Why is reference sometimes needed in callback body and sometimes not?

⚓ Rust    📅 2026-06-22    👤 surdeus    👁️ 1      

surdeus

I'm reading Closures That Capture Their Environment in the Rust book.

The example defines this function:

let in_my_size = shoes_in_size(shoes, 10);
fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
    shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}

I'm struggling to understand why this code I wrote needs to use references:

let filtered_list = values_greater_than(some_list, 1);

This won't compile:

fn values_greater_than(numbers: Vec<i32>, lower_limit: i32) -> Vec<i32> {
    numbers.into_iter().filter(|x| x > lower_limit).collect()
}
numbers.into_iter().filter(|x| x > lower_limit).collect()
                                   ^^^^^^^^^^^ expected `&i32`, found `i32`

Any of these work:

numbers.into_iter().filter(|x| *x > lower_limit).collect()
numbers.into_iter().filter(|x| x > &lower_limit).collect()

What makes my code different from book example?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed