Consider this piece of code:
struct Collector<T>
where
T: Iterator<Item = char>,
{
current: u32,
right_neighbour: u32,
counter: usize,
iterator: T,
}
impl<T: Iterator<Item = char>> Collector<T> {
fn next(&self) -> u32 {
self.iterator
.next()
.expect("failed to get next digit!")
.to_digit(10)
.expect("failed to prase char as digit!")
}
fn collect(&self) {
self.current = self.right_neighbour;
self.right_neighbour = self.next();
self.counter = self.counter + 1;
}
fn initialize<U>(iterator: U) -> Collector<U>
where
U: Iterator<Item = char>,
{
let mut collector = Collector {
current: 0,
right_neighbour: 0,
counter: 0,
iterator: iterator,
};
collector.collect();
collector
}
}
fn main() {
let numstr = "1111";
let mut collector = Collector::initialize(numstr.chars().cycle().peekable());
}
It produces a type mismatch error:
error[E0284]: type annotations required: cannot resolve `<_ as std::iter::Iterator>::Item == char`
--> src/main.rs:46:25
|
46 | let mut collector = Collector::initialize(numstr.chars().cycle().peekable());
| ^^^^^^^^^^^^^^^^^^^^^
|
= note: required by `<Collector<T>>::initialize`
What is the type of numstr.chars().cycle().peekable()
? The compiler tells me that its full type is:
std::iter::Peekable<std::iter::Cycle<std::str::Chars<'_>>>
I know that I can't use that type in the definition of my structs/functions, because it doesn't have an explicit lifetime...
How can I correctly write this code?