3

I am working on my first Rust project, learning as I go. I am trying to filter a vector of &str, however when I attempt to collect the iterator I get this error:

a value of type `std::vec::Vec<&str>` cannot be built from an iterator over elements of type `&&str`

The documentation of filter does mention the situation where you get a double reference, following the advice in the documentation I have tried destructuring the references in the argument to the closure, I also have tried adding single or double dereference on the body of the closure.

let test = vec!("a", "b", "", "c");
let filt_a: Vec<&str> = tst.iter().filter(|&&x| x.is_empty()).collect();
let filt_b: Vec<&str> = tst.iter().filter(|&x| *x.is_empty()).collect();
let filt_c: Vec<&str> = tst.iter().filter(|x| **x.is_empty()).collect();

Any fewer dereferences (or destructured references) also result in exactly the same error.

Adding any additional dereferences just results in the error when you try and dereference a plain &str.

Any advice to get me on the right path would be wonderful.

Sam F.H.
  • 141
  • 2
  • 8
  • 4
    You need `.copied()` after the filter, or `into_iter()` instead of `iter()`. The latter will result in consuming the original vector. – Sven Marnach Aug 10 '20 at 15:56
  • Perfect, thank you! Just tried them both, I couldnt use 2 dereferences when I use `into_iter()`. `.copied` worked with any of the combinations of dereferences. – Sam F.H. Aug 10 '20 at 16:01
  • 3
    Related: [Do iterators return a reference to items or the value of the items in Rust?](https://stackoverflow.com/questions/60780389/do-iterators-return-a-reference-to-items-or-the-value-of-the-items-in-rust) [What is the difference between iter and into_iter?](https://stackoverflow.com/questions/34733811/what-is-the-difference-between-iter-and-into-iter) [Iterating over a slice's values instead of references in Rust?](https://stackoverflow.com/questions/40613725/iterating-over-a-slices-values-instead-of-references-in-rust) – Sven Marnach Aug 10 '20 at 16:01

1 Answers1

3

As Sven Marnach very helpfully pointed out I either needed either .copied() after filter or .into_iter() instead of .iter().

Docs for copied

Docs for into_iter for Vec

Sam F.H.
  • 141
  • 2
  • 8