Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to have a iterator over the references of a given numeric range?

Tags:

rust

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
like image 783
Allen Lee Avatar asked Dec 10 '25 11:12

Allen Lee


1 Answers

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
}
like image 91
Tim Visée Avatar answered Dec 12 '25 02:12

Tim Visée



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!