One way of doing this is to create an array or vector ([0, 1, 2, ..., n] and then use the iter() method. However, it is not memory efficient at all.
I tried the following implementation:
pub struct StaticIxIter {
max: usize,
current: usize,
next: usize,
}
impl StaticIxIter {
pub fn new(max: usize) -> Self {
StaticIxIter {
max,
current: 0,
next: 0,
}
}
}
impl Iterator for StaticIxIter {
type Item = &usize;
fn next(&mut self) -> Option<Self::Item> {
if self.next >= self.max {
return None;
}
self.current = self.next;
self.next += 1;
Some(&self.current)
}
}
fn main() {
for element in StaticIxIter::new(10) {
println!("{}", element);
}
}
It won't compile:
error[E0106]: missing lifetime specifier
--> src/main.rs:18:17
|
18 | type Item = &usize;
| ^ expected lifetime parameter
For iterating over a list of numbers, you might want to use Rust's range iterator.
Take a look at this iterator example, where a range is used:
for element in 0..100 {
println!("{}", element);
}
Changing this to 0..max is also perfectly fine. Don't forget to wrap this range between brackets like (0..100).map(...) if you want to use iterator functions on it.
About borrowing; for borrowing iterator items, you need to have an owner for them. I recommend to keep your implementation as simple as possible. Why don't you borrow iterator items after you iterated over it, like this?
for element in 0..100 {
println!("{}", &element);
// ^- borrow here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With