简体   繁体   English

在给定数值范围的引用上使用迭代器的最有效方法是什么?

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

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. 一种方法是创建一个数组或向量( [0, 1, 2, ..., n] ,然后使用iter()方法。但是,它根本不是内存效率。

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 . 对于遍历数字列表,您可能希望使用Rust的范围迭代器

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. 将此更改为0..max也非常好。 Don't forget to wrap this range between brackets like (0..100).map(...) if you want to use iterator functions on it. 如果要在其上使用迭代器函数,请不要忘记在(0..100).map(...)等括号之间包装此范围。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM