Rust Error: Value of Type `Std: :Vec: :Vec` Cannot Be Built from `Std: :Iter: :Iterator`

I am new to rust and encountered the error

std::vec::Vec<i32> cannot be built from std::iter::Iterator<Item=&i32>

when trying to use a function get_even_numbers() to borrow v by passing it in by reference &v instead of by value v.

fn main() {
    let v: Vec<i32> = (0..10).collect();
    let even: Vec<i32> = get_even_numbers(&v);
    println!("Even numbers: {:?}", even);
}

fn get_even_numbers(v: &Vec<i32>) -> Vec<i32> {
    v.iter().filter(|x| x % 2 == 0).collect()
}

Why does the above give an error, but passing it in by value does not, as shown below?

Additionally, I used .iter() inside the function when passing in by reference and .into_iter() when passing in by value, not sure if these are the correct functions to use.

fn main() {
    let v: Vec<i32> = (0..10).collect();
    let even: Vec<i32> = get_even_numbers(v);
    println!("Even numbers: {:?}", even);
}

fn get_even_numbers(v: Vec<i32>) -> Vec<i32> {
    v.into_iter().filter(|x| x % 2 == 0).collect()
}

// Even numbers: [0, 2, 4, 6, 8]
1

1 Answer

Use v.iter().filter(|x| x % 2 == 0).cloned().collect(). That will (trivially) clone each of the &i32 references into actual i32 values.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest