我在徘徊是否有一种方法来初始化带有项目列表的Iterator序列(类似于您使用Vector<String>
初始化vec![1, 2, 3]
的方式)。
我尝试过在线搜索与我需要的东西类似的东西,但是什么也没找到。我知道其他语言(例如Java的Stream.of
)中也存在此功能。
这是我的用例(摘自Rust Book中解释的minigrep示例的变体):
...
pub fn grep<'a>(to_search_into: &'a str, pattern: &'a str) -> impl Iterator<Item = &'a str> {
to_search_into.lines()
.filter(move |line| line.contains(pattern))
}
...
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let test_string = "\
I am Grogg the everlasting
The great potato eater of old
Beware my ravenous maws.";
assert_eq!(
grep(test_string, "Grogg"),
// what should go here?
iter!["Grogg"]
);
}
}