Hi all,
I've been experimenting with rust iterator, and stucked with this problem. I want to have a struct that holds an iterator to some type (in this case, let's say it's a string). But it's actually not just an iterator, but iterator with some filter and rev applied to it. I put the code below.
But for some reason, it doesn't work if I put it inside an impl
block. But it works fine with free function that returns SomeStruct<impl Iterator<...>>
.
I understand why it works on free function. But, not quite sure why it doesn't work on impl-scoped function. Do I need to explicitly write the concrete type like Iterator<Rev<Filter<...>>>
? Is there a better way to do this?
use std::iter::Peekable;
struct SomeStruct<T>
where
T: Iterator<Item = String>,
{
data: Peekable<T>,
}
fn new(s: Vec<String>) -> SomeStruct<impl Iterator<Item=String>> {
SomeStruct{
data: s.into_iter().rev().filter(|s| s != "hahaha").peekable(),
}
}
impl<T> SomeStruct<T>
where
T: Iterator<Item = String>,
{
fn new(s: Vec<String>) -> Self {
Self {
data: s.into_iter().rev().filter(|s| s != "hahaha").peekable(),
}
}
}
fn main() {}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/main.rs:22:19
|
16 | impl<T> SomeStruct<T>
| - this type parameter
...
22 | data: s.into_iter().rev().filter(|s| s != "hahaha").peekable(),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected type parameter `T`, found struct `Filter`
|
= note: expected struct `Peekable<T>`
found struct `Peekable<Filter<Rev<std::vec::IntoIter<String>>, [closure@src/main.rs:22:46: 22:49]>>`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error