在 Rust 中为具有字段 HashSet 的结构实现迭代器

问题描述 投票:0回答:1

我喜欢为 struct FileSystem 实现一个迭代器:

pub struct FileSystem <'a>  {
    file_system: HashSet::<FileContent>,
    iter: hash_set::Iter<'a,FileContent>,
}

impl <'a>  FileSystem  <'a> {
    pub fn new() -> FileSystem <'a>  {
        let fs = HashSet::<FileContent>::new();
        let iter = fs.iter();
        FileSystem {file_system:fs,iter:iter}
    }
}

impl <'a> Iterator for FileSystem <'a>  {
    type Item =  &'a FileContent;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }
}

只是为了隐藏HashSet字段file_content。

但是我所有的尝试都失败了。我对 Rust 还很陌生,这将是我第一次实现迭代器。

在这种特殊情况下,编译器会抱怨:

cannot return value referencing local variable `fs`

let iter = fs.iter()
           -- `fs` is borrowed here
FileSystem {file_system:fs,iter:iter}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function

我以某种方式得到了这个,但不知道如何链接“iters”或如何存储迭代器的状态?

非常感谢

rust iterator
1个回答
0
投票

我会做这样的事情(希望它有帮助!)

use std::collections::HashSet;

pub struct FileSystem {
    file_system: HashSet<FileContent>,
}

impl FileSystem {
    pub fn new() -> FileSystem {
        let fs = HashSet::<FileContent>::new();
        FileSystem { file_system: fs }
    }

    pub fn iter(&self) -> impl Iterator<Item = &FileContent> {
        self.file_system.iter()
    }
}


fn main() {
    let fs = FileSystem::new();

    for file_content in fs.iter() {
        println!("{:?}", file_content);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.