I tried to write a generic iterator, but I do not see how to return value without using clone
. Is there any way to create a variable within the next
function and return a reference? If I replace T
with u32
, then I can just return Some(self.count)
, but using generics, it is not possible.
use num_traits::Num;
use std::clone::Clone;
struct Counter<T>
where
T: Num + Clone,
{
count: T,
}
impl<T> Counter<T>
where
T: Num + Clone,
{
fn new() -> Counter<T> {
Counter { count: T::zero() }
}
}
impl<T> Iterator for Counter<T>
where
T: Num + Clone,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.count = self.count.clone() + T::one();
Some(self.count.clone())
}
}
fn main() {
let mut number: Counter<u32> = Counter::new();
match number.next() {
Some(x) => println!("Number {}", x),
None => println!("Invalid"),
}
}