Function std::iter::once_with

1.43.0 · source ·
pub fn once_with<A, F>(gen: F) -> OnceWith<F> where
    F: FnOnce() -> A,
Expand description

创建一个迭代器,该迭代器通过调用提供的闭包来懒惰地一次生成一个值。

这通常用于使单个值生成器适应其他类型的迭代的 chain()。 也许您有一个涵盖几乎所有内容的迭代器,但是您需要一个额外的特殊情况。 也许您有一个可在迭代器上使用的函数,但只需要处理一个值即可。

once() 不同,此函数将根据要求延迟生成值。

Examples

基本用法:

use std::iter;

// 一个是最孤独的数字
let mut one = iter::once_with(|| 1);

assert_eq!(Some(1), one.next());

// 只是一个,这就是我们得到的
assert_eq!(None, one.next());
Run

与另一个迭代器链接在一起。 假设我们要遍历 .foo 目录的每个文件,还要遍历一个配置文件,

.foorc:

use std::iter;
use std::fs;
use std::path::PathBuf;

let dirs = fs::read_dir(".foo").unwrap();

// 我们需要将 DirEntry-s 的迭代器转换为 PathBufs 的迭代器,因此我们使用 map
let dirs = dirs.map(|file| file.unwrap().path());

// 现在,我们的迭代器仅用于我们的配置文件
let config = iter::once_with(|| PathBuf::from(".foorc"));

// 将两个迭代器链接到一个大迭代器中
let files = dirs.chain(config);

// 这将为我们提供 .foo 和 .foorc 中的所有文件
for f in files {
    println!("{f:?}");
}
Run