有没有更好的方法来编写返回迭代器的方法?

问题描述

我有一个名为 Finder 的结构,用于在字符串列表中搜索单词:

fn main() {
    let lines = vec![
        "The first line.","And the second one.","The very last line.",];
    let word = "the";
    let iter = lines.iter().map(|x| String::from(*x));

    let finder = Finder::new();

    for matched in finder.find(iter,word) {
        println!("{:?}",matched);
    }
}

pub struct Finder {
    ignore_case: bool,}

#[derive(Debug)]
pub struct Match {
    line_no: usize,offset: usize,line: String,}

impl Finder {
    pub fn new() -> Finder {
        Finder { ignore_case: true }
    }

    pub fn find<'a,I: 'a>(
        &'a self,lines: I,word: &'a str,) -> impl std::iter::Iterator<Item = Match> + 'a
    where
        I: std::iter::Iterator<Item = String>,{
        let word = String::from(word);

        lines
            .enumerate()
            .filter_map(move |(i,line)| match self.find_word(&line,&word) {
                Some(index) => Some(Match {
                    line_no: i,offset: index,line: String::from(line),}),None => None,})
    }

    fn find_word(&self,line: &str,word: &str) -> Option<usize> {
        if self.ignore_case {
            line.to_lowercase().find(&word.to_lowercase())
        } else {
            line.find(word)
        }
    }
}

我想说这个实现比它应该的间接要多得多,但我想更好地探索可用语言的特性。

方法 find 接受一个迭代器,并返回产生 Match 结果的迭代器。代码按预期工作,但感觉相当复杂! find 方法的签名包括模板、生命周期和其他对我这个新手来说很棘手的东西。

有没有更好的方法方法中返回迭代器?我可以使用简单的函数和结构来实现相同的逻辑,或者只是在 vector 上调用 filter_map,但我的目标是更好地掌握语言的功能

是否可以从一个方法返回一个迭代器,但有一个更简单方法签名,或者在这种情况下是否期望有这样一个“详细”的签名?

这段代码是在编译器的帮助下编写的,也就是说,我一个一个地修复错误,直到它起作用为止。 Rust 专业人士会用同样的方式写这个,还是有更好的方法

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)