How to Collect the Iterator created by Vec::windows()

I am trying to iterate over slices of a Vec so I can do a custom check to see if the element is a duplicate. To iterate over slices I am using the .window() method which returns an Iterator. However, Iterator.collect() fails in this case.

fn main() {
    // Working 
    let v0: Vec<&str> = vec!["a", "b", "c"];
    let v2: Vec<&str> = v0.clone().into_iter().collect();
    assert_eq!(&v0, &v2);

    // Not working, see error 
    let v3: Vec<&str> = v0.clone().windows(2).collect();
    assert_eq!(&v0, &v3);
}

```rust
error[E0277]: a value of type `Vec<&str>` cannot be built from an iterator over elements of type `&[&str]`
    --> src/main.rs:8:47
     |
8    |     let v3: Vec<&str> = v0.clone().windows(2).collect();
     |                                               ^^^^^^^ value of type `Vec<&str>` cannot be built from `std::iter::Iterator<Item=&[&str]>`
     |
     = help: the trait `FromIterator<&[&str]>` is not implemented for `Vec<&str>`
     = help: the trait `FromIterator<&str>` is implemented for `Vec<&str>`
     = help: for that trait implementation, expected `str`, found `[&str]`
note: required by a bound in `collect`

How do I get a Vec out of the Vec<&[T]> produced by .windows()?

1 Like

You can’t re-use the same variable, because the new value has a different type than the old one. You can use let to create a new variable with a different name:

 let v2: Vec<&[&str]> = v.windows(2).collect();

or even a new variable with the same name:

let v: Vec<&[&str]> = v.windows(2).collect();
// The old `v` still exists but is shadowed and can no longer be named.
1 Like

Hello!

When you post, we'd appreciate it if you could please format code the described here:
https://users.rust-lang.org/t/forum-code-formatting-and-syntax-highlighting/42214

You've probably already gotten an answer, but it would be nice to edit your post anyway for future readers.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.