#iterator #macro

iter_vals

即时迭代器创建

1 个不稳定版本

0.1.0 2019年6月26日

#1408 in Rust 模式

MIT/Apache

10KB
57

iter_vals

此软件包允许即时创建迭代器。

示例

您可以使用它来返回字面量的迭代器

use iter_vals::iter_vals;

#[derive(Debug, PartialEq)]
enum Media {
    Book,
    Newspaper,
    TV,
    PC,
}

use Media::*;

impl Media {
    fn digital() -> impl Iterator<Item = Media> {
        iter_vals!(TV, PC)
    }

    fn non_digital() -> impl Iterator<Item = Media> {
        iter_vals!(Book, Newspaper)
    }
}

let mut digital = Media::digital();
assert_eq!(digital.next(), Some(TV));
assert_eq!(digital.next(), Some(PC));
assert_eq!(digital.next(), None);

let mut non_digital = Media::non_digital();
assert_eq!(non_digital.next(), Some(Book));
assert_eq!(non_digital.next(), Some(Newspaper));
assert_eq!(non_digital.next(), None);

您可以根据条件包含值。这可以用来返回不同数量的值,而不需要分配

use iter_vals::iter_vals;

fn next_numbers(start: i32, include_first_number: bool) -> impl Iterator<Item = i32> {
    iter_vals!(
        [..= include_first_number; start + 1],
        (start + 2),
        (start + 3)
    )
}

let mut next_nums = next_numbers(5, true);
assert_eq!(next_nums.next(), Some(6));
assert_eq!(next_nums.next(), Some(7));
assert_eq!(next_nums.next(), Some(8));
assert_eq!(next_nums.next(), None);

let mut next_nums = next_numbers(5, false);
assert_eq!(next_nums.next(), Some(7));
assert_eq!(next_nums.next(), Some(8));
assert_eq!(next_nums.next(), None);

您可以在返回的迭代器内部展开其他迭代器。当处理 Option 时,这特别有用

use iter_vals::iter_vals;

fn make_iter(num1: i32, num2: Option<i32>, num3: i32) -> impl Iterator<Item = i32> {
    iter_vals!(
        num1,
        [.. num2],
        num3
    )
}

let mut nums = make_iter(1, Some(2), 3);
assert_eq!(nums.next(), Some(1));
assert_eq!(nums.next(), Some(2));
assert_eq!(nums.next(), Some(3));
assert_eq!(nums.next(), None);

let mut nums = make_iter(1, None, 3);
assert_eq!(nums.next(), Some(1));
assert_eq!(nums.next(), Some(3));
assert_eq!(nums.next(), None);

let mut nums = iter_vals!(1, [.. vec![2, 2]], 3);
assert_eq!(nums.next(), Some(1));
assert_eq!(nums.next(), Some(2));
assert_eq!(nums.next(), Some(2));
assert_eq!(nums.next(), Some(3));
assert_eq!(nums.next(), None);

注意

如果您想返回计算值,由于宏系统的限制,您目前必须将它们放在括号中才能使其工作

这将 不会 工作

use iter_vals::iter_vals;

let nums: Vec<_> = iter_vals!(1 + 1, 2 + 2, 3 + 3).collect();
assert_eq!(nums, vec![2, 4, 6]);

但这是可以的

use iter_vals::iter_vals;

let nums: Vec<_> = iter_vals!((1 + 1), (2 + 2), (3 + 3)).collect();
assert_eq!(nums, vec![2, 4, 6]);

无运行时依赖