迭代 collection。 Iterator 被删除后立即删除它

Iterate over collection. Drop it as soon as Iterator is dropped

我已将 collections 转储到磁盘上。当请求时,应该检索这些 collections(没问题)并且应该为它构建一个 iterator,returns 引用检索到的值。

删除iterator后,我不再需要collection了。我也希望它被删除。

到目前为止我尝试过的:

  1. Iterator 拥有 collection。这对我来说最有意义,但这是不可能的;我不太清楚为什么。有人说 Iterator 特征的 next 方法签名是问题所在。 (example)

  2. 引用计数:Retrieverreturn是Rc<Vec<usize>>。我 运行 遇到了与拥有迭代器相同的问题。 (example)

  3. 让猎犬拥有 collection 并分发对它的引用。我尝试实现具有内部可变性 (RefCell<HashMap>) 的检索器,但我无法 return 引用具有足够长生命周期的 HashMap

我看到了两种基本的可能性。

  1. 寻回犬 t运行 转让所有权。然后 Iterator 需要拥有数据。内容如下:

    use std::slice::Iter;
    
    fn retrieve(id: usize) -> Vec<usize> {
        //Create Data out of the blue (or disk, or memory, or network. I dont care)
        //Move the data out. Transfer ownership
        let data = vec![0, 1, 2, 3];
        data
    }
    
    fn consume_iterator<'a, TIterator: Iterator<Item=&'a usize>>(iterator: TIterator) {
        for i in iterator {
            println!("{}", i);
        }
    }
    
    fn handler<'a>(id: usize) -> Iter<'a, usize> {
        //handle_request now owns the vector.
        //I now want to build an owning iterator..
        //This does of course not compile as vector will be dropped at the end of this method
        retrieve(id).iter()
    }
    
    fn main() {
        consume_iterator(handler(0))
    }
    
  2. 猎犬拥有 collection。但是接下来又出现了两个新的问题:

    1. 当迭代器超出 运行ge 时如何删除数据?
    2. 如何告诉 borrow-checker 我将拥有 collection 足够长的时间?

    use std::cell::{Ref, RefCell};
    
    struct Retriever {
        //Own the data. But I want it to be dropped as soon as the references to it go out of scope.
        data: RefCell<Vec<usize>>
    }
    
    impl Retriever{
    
        fn retrieve<'a>(&'a self, id: usize) -> Ref<'a, Vec<usize>> {
            //Create Data out of the blue (or disk, or memory, or network. I dont care)
            //Now data can be stored internally and a referece to it can be supplied.
            let mut data = self.data.borrow_mut();
            *data = vec![0, 1, 2, 3];
            self.data.borrow()
        }
    
    }
    
    fn consume_iterator<'a, TIterator: Iterator<Item=&'a usize>>(iterator: TIterator) {
        for i in iterator {
            println!("{}", i);
        }
    }
    
    
    fn handler<'a>(ret: &'a Retriever, id: usize) -> IterWrapper<'a> {
        //andle_request now has a reference to the collection
        //So just call iter()? Nope. Lifetime issues.
        ret.retrieve(id).iter()        
    }
    
    fn main() {
        let retriever = Retriever{data: RefCell::new(Vec::new())};
        consume_iterator(handler(&retriever, 0))
    }
    

我觉得这里有点迷茫,我忽略了一些明显的东西。

The Iterator owns the collection. [or joint ownership via reference-counting]

ContainerIterator { 
    data: data,
    iter: data.iter(),
}

不,你cannot have a value and a reference to that value in the same struct.

Letting the retriever own the collection and handing out a reference to it.

不,你cannot return references to items owned by the iterator.

正如评论者所说,使用 IntoIter 将项目的所有权转移到迭代器,然后将它们作为迭代值分发出去:

use std::vec::IntoIter;

struct ContainerIterator {
    iter: IntoIter<usize>,
}

impl Iterator for ContainerIterator {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

fn main() {
    let data = vec![0, 1, 2, 3];
    let cont = ContainerIterator { iter: data.into_iter() };

    for x in cont {
        println!("Hi {}", x)
    }
}

如果您必须 return 引用...那么您需要在所有引用可能存在的整个时间内保留拥有它们的东西。

How can I drop the data when the iterator is out of range?

不再使用该值:

fn main() {
    {
        let loaded_from_disk = vec![0, 1, 2, 3];
        for i in &loaded_from_disk {
            println!("{}", i)
        }
        // loaded_from_disk goes out of scope and is dropped. Nothing to *do*, per se.
    }
}

How do I tell the borrow-checker that I will own the collection long enough?

通过拥有 collection 足够长的时间。没有 Rust Illuminati 与借用检查器使用的秘密握手。代码只需要结构化,使得借用的东西在借用未完成时不会变得无效。你不能移动它(改变内存地址)或放下它(改变内存地址)。

我现在终于能够实施一个相对令人满意的解决方案:

Cells 内隐藏迭代器的可变性:

pub trait OwningIterator<'a> {
    type Item;
    fn next(&'a self) -> Option<Self::Item>;
}

一个结构现在需要一个 Celld 位置来允许迭代而不改变。 作为一个例子,这里是一个结构的实现,它既拥有又可以迭代 Arc<Vec<T>>:

pub struct ArcIter<T> {
    data: Arc<Vec<T>>,
    pos: Cell<usize>,
}

impl<'a, T: 'a> OwningIterator<'a> for ArcIter<T> {
    type Item = &'a T;

    fn next(&'a self) -> Option<Self::Item> {
        if self.pos.get() < self.data.len() {
            self.pos.set(self.pos.get() + 1);
            return Some(&self.data[self.pos.get() - 1]);
        }  
        None
    }
}

因为我能够将这些类型的迭代器隐藏在接口后面,让用户只处理 "real" 个迭代器,所以我觉得这是可以接受的偏离标准的情况。

感谢所有提出想法并最终帮助我找到解决方案的人。